package com.ruoyi.feike.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.activiti.domain.ActRuIdentitylink;
import com.google.common.base.Joiner;
import com.ruoyi.activiti.domain.ActWorkflowFormData;
import com.ruoyi.activiti.domain.dto.ActTaskDTO;
import com.ruoyi.activiti.domain.vo.SearchVo;
import com.ruoyi.activiti.mapper.ActRuIdentitylinkMapper;
import com.ruoyi.activiti.mapper.ActWorkflowFormDataMapper;
import com.ruoyi.activiti.service.IActWorkflowFormDataService;
import com.ruoyi.activiti.service.impl.ActTaskServiceImpl;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.CustomPage;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.AsposeUtil;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.dto.WaitForSaveNoteDTO;
import com.ruoyi.feike.domain.dto.YearAuditSaveDTO;
import com.ruoyi.feike.domain.vo.*;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.*;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.identity.UserGroupManager;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.runtime.shared.security.SecurityManager;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.model.payloads.GetTasksPayload;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableUpdate;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.runtime.api.model.impl.APITaskConverter;
import org.activiti.runtime.api.query.impl.PageImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * feikeService业务层处理
 *
 * @author ruoyi
 * @date 2022-07-07
 */
@Service
@Slf4j
public class AnnualReviewyServiceImpl implements IAnnualReviewyService {
    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    @Autowired
    private ContractApprovalMapper contractApprovalMapper;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private DetailInformationMapper detailInformationMapper;

    @Autowired
    private DealerInformationMapper dealerInformationMapper;

    @Autowired
    private WholesalePerformanceCurrentlyMapper wholesalePerformanceCurrentlyMapper;

    @Autowired
    private WholesalePerformanceRecentThreeMonthsMapper wholesalePerformanceRecentThreeMonthsMapper;

    @Autowired
    private SalesPerformanceAndTargetMapper salesPerformanceAndTargetMapper;

    @Autowired
    private LimitCalculationForCommericalNeedsMapper limitCalculationForCommericalNeedsMapper;

    @Autowired
    private OtherFinancingResourceMapper otherFinancingResourceMapper;

    @Autowired
    private TemporaryConditionFollowUpMapper temporaryConditionFollowUpMapper;

    @Autowired
    private ProposalByCommericalAndMarketingMapper proposalByCommericalAndMarketingMapper;

    @Autowired
    private SecuritiesMapper securitiesMapper;

    @Autowired
    private IApprovalStatusReportService approvalStatusReportService;

    @Autowired
    private NotesMapper notesMapper;

    @Autowired
    private CreditConditionMapper creditConditionMapper;

    @Autowired
    private ApprovedLimitAndConditionMapper approvedLimitAndConditionMapper;

    @Autowired
    private ProcessRuntime processRuntime;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IDealerNegativeInformationCheckService dealerNegativeInformationCheckService;

    @Autowired
    private TaskRuntime taskRuntime;

    @Autowired
    private UserGroupManager userGroupManager;

    @Autowired
    private SecurityManager securityManager;

    @Autowired
    private APITaskConverter taskConverter;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ICreditConditionService creditConditionService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private IFileuploadService fileuploadService;
    @Autowired
    private IActWorkflowFormDataService actWorkflowFormDataService;

    @Autowired
    private WholesalePerformanceRecentMapper wholesalePerformanceRecentMapper;

    @Autowired
    private SalesPerformanceAndTargetOrcaleMapper salesPerformanceAndTargetOrcaleMapper;

    @Autowired
    private IDealerInformationService dealerInformationService;

    @Autowired
    private IGradeService gradeService;

    @Autowired
    private SectorInformationMapper sectorInformationMapper;

    @Autowired
    private PlmMapper plmMapper;

    @Autowired
    private LoyaltyPerformance4qMapper loyaltyPerformance4qMapper;

    @Autowired
    private LoyaltyPerformance6monthMapper loyaltyPerformance6monthMapper;

    @Autowired
    private ActRuIdentitylinkMapper actRuIdentitylinkMapper;
    @Autowired
    private ActiveLimitAdjustmentProposalMapper activeLimitAdjustmentProposalMapper;
    @Autowired
    private CbFleetDetailsMapper cbFleetDetailsMapper;
    @Autowired
    private BalanceInformationMapper balanceInformationMapper;

    @Autowired
    private ContractRecordMapper contractRecordMapper;

    @Autowired
    private HDealerDmMapper hDealerDmMapper;

    @Autowired
    private HAmlMapper amlMapper;
    @Autowired
    private HRptMapper rptMapper;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private InstanceIdUtil instanceIdUtil;

    @Autowired
    private ActWorkflowFormDataMapper actWorkflowFormDataMapper;

    @Autowired
    private DealercodeContractFilingMapper dealercodeContractFilingMapper;

    @Autowired
    private  IActWorkflowLockService  iActWorkflowLockService;

    @Autowired
    private IDealercodeContractService dealercodeContractService;

    @Autowired
    private DealercodeContractMapper dealercodeContractMapper;

    @Autowired
    private ActTaskServiceImpl actTaskService;

    @Autowired
    private SysDbOperLogMapper sysDbOperLogMapper;

    @Autowired
    private HBasicCorporateGuaranteeMapper basicCorporateGuaranteeMapper;

    @Autowired
    private HBasicCorporateMapper basicCorporateMapper;

    /**
     * 查询feike
     *
     * @param id feikeID
     * @return feike
     */
    @Override
    public Map<String, Object> selectAnnualReviewyById(String id) {
        Map<String, Object> map = new HashMap<>();  //一级
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId1(id);
        if (annualReviewy != null) {
            map.put("id", annualReviewy.getId()); // id
            map.put("instanceId", annualReviewy.getInstanceId()); // instanceId
            map.put("title", annualReviewy.getTitle()); // 标题
            map.put("createTime", annualReviewy.getCreateTime()); // 创建时间
            map.put("createName", annualReviewy.getCreateName()); // 发起人中午名称
            map.put("createBy", annualReviewy.getCreateBy()); // 发起人用户名称
            map.put("username", annualReviewy.getLockname()); // 发起人用户名称
        }
        Map<String, Object> data = new HashMap<>();  // 二级
        List<Map<String, Object>> childrenList = new ArrayList();
        Map<String, Object> groupName = new HashMap<>();
        Map<String, Object> children = new HashMap<>();

        // List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(annualReviewy.getInstanceId());
        // if (basicInformationList != null && basicInformationList.size() > 0) {
        //     for (BasicInformation basicInformation : basicInformationList) {
        //         groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
        //         groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN
        //     }
        // }
        List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(annualReviewy.getInstanceId());
        if (basicInformationList != null && basicInformationList.size() > 0) {
            for (BasicInformation basicInformation : basicInformationList) {
                groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
                groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN

                children.put("basicInformationId", basicInformation.getId());
                children.put("instanceId", basicInformation.getInstanceId());
                children.put("GM", basicInformation.getGm());
                children.put("dealerCodeFromManufacturer", basicInformation.getDealerCodeFromManufacturer());
                children.put("dealerCodeFromWFS", basicInformation.getDealerCodeFromWFS());
                children.put("dealerNameCN", basicInformation.getDealerNameCN());
                children.put("dealerNameEN", basicInformation.getDealerNameEN());
                children.put("dealername", basicInformation.getDealername());
                children.put("incorporationDate", basicInformation.getIncorporationDate());
                children.put("joinSectorDealerNetworkDate", basicInformation.getJoinSectorDealerNetworkDate());
                children.put("paidupCapital", basicInformation.getPaidupCapital());
                children.put("province", basicInformation.getProvince());
                children.put("relatedWorkingExperience", basicInformation.getRelatedWorkingExperience());
                children.put("value", basicInformation.getDealerValue());

                String[] split = basicInformation.getSector().split(",");
                children.put("sector", split);
                children.put("shareholdersAndShare", basicInformation.getShareholders());
            }
        }
        data.put("groupName", groupName); // groupNameEN
        // Map<String, Object> children = new HashMap<>();
        List<SalesPerformanceAndTarget> salesPerformanceAndTargetList = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(annualReviewy.getInstanceId());
        if (salesPerformanceAndTargetList != null && salesPerformanceAndTargetList.size() > 0) {
            children.put("sales_performance_and_target", salesPerformanceAndTargetList);
        }

        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeedList = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(annualReviewy.getInstanceId());
        if (limitCalculationForCommericalNeedList != null && limitCalculationForCommericalNeedList.size() > 0) {
            children.put("limit_calculation_for_commerical_needs", limitCalculationForCommericalNeedList);
        }

        List<OtherFinancingResource> otherFinancingResourceList = otherFinancingResourceMapper.selectOtherFinancingResourceByInstanceId(annualReviewy.getInstanceId());
        if (otherFinancingResourceList != null && otherFinancingResourceList.size() > 0) {
            children.put("other_financing_resource", otherFinancingResourceList);
        }

        List<TemporaryConditionFollowUp> temporaryConditionFollowUpList = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByInstanceId(annualReviewy.getInstanceId());
        if (temporaryConditionFollowUpList != null && temporaryConditionFollowUpList.size() > 0) {
            children.put("temporary_condition_follow_up", temporaryConditionFollowUpList);
        }

        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingList = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(annualReviewy.getInstanceId());
        if (proposalByCommericalAndMarketingList != null && proposalByCommericalAndMarketingList.size() > 0) {
            children.put("proposal_by_commerical_and_marketing", proposalByCommericalAndMarketingList);
        }

        List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingBySubProcessId(annualReviewy.getInstanceId());
        if (dealercodeContractFilings != null && dealercodeContractFilings.size() > 0) {
            children.put("contract_sub_process_list", dealercodeContractFilings);
        }

        List<Securities> securitieList = securitiesMapper.selectSecuritiesByInstanceId(annualReviewy.getInstanceId());

        Collections.sort(securitieList, new Comparator<Securities>() {
            @Override
            public int compare(Securities o1, Securities o2) {
                return PingyinUtil.getUpperCase(o1.getCurrentNameCN(),false).compareTo(PingyinUtil.getUpperCase(o2.getCurrentNameCN(),false));
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });
        Collections.sort(securitieList, new Comparator<Securities>() {
            @Override
            public int compare(Securities o1, Securities o2) {
                return o1.getGuaranteeType().compareTo(o2.getGuaranteeType());
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });
        Collections.sort(securitieList, new Comparator<Securities>() {
            @Override
            public int compare(Securities o1, Securities o2) {
                return o1.getDealername().compareTo(o2.getDealername());
            }

            @Override
            public boolean equals(Object obj) {
                return false;
            }
        });
        if (securitieList != null && securitieList.size() > 0) {
            children.put("securities", securitieList);
        }
        childrenList.add(children);
        data.put("children", childrenList);
        Notes notes = notesMapper.selectNotesByInstanceId(annualReviewy.getInstanceId());
        if (notes != null) {
            data.put("basicNotes", notes.getBasicNotes());
            data.put("guaranteeNotes", notes.getGuaranteeNotes());
            data.put("amlNotes", notes.getAmlNotes());
            data.put("loyaltyNotes", notes.getLoyaltyNotes());
            data.put("auditNotes", notes.getAuditNotes());
            data.put("wholesaleNotes", notes.getWholesaleNotes());
            data.put("proposalNotes", notes.getProposalNotes());
            data.put("dealerNotes", notes.getDealerNotes());
            data.put("comments", notes.getComments());
            data.put("conditionNotes", notes.getConditionNotes());

        }
        map.put("data", data);
        return map;
    }

    /**
     * 查询feike列表
     *
     * @param annualReviewy feike
     * @return feike
     */
    @Override
    public List<AnnualReviewyHistoryVO> selectAnnualReviewyList(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        return annualReviewyMapper.selectAnnualReviewyListBySelf(annualReviewy, basicInformation, SecurityUtils.getLoginUser()
                .getUsername());
    }

    public List<AnnualReviewyHistoryVO> selectAnnualReviewyList1(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        return annualReviewyMapper.selectAnnualReviewyListBySelf1(annualReviewy, basicInformation, SecurityUtils.getLoginUser()
                .getUsername());
    }

    public List<AnnualReviewyHistoryVO> selectAnnualReviewyList2(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        return annualReviewyMapper.selectAnnualReviewyListBySelf2(annualReviewy, basicInformation, SecurityUtils.getLoginUser()
                .getUsername());
    }

    public List<AnnualReviewyHistoryVO> selectAnnualReviewyList3(AnnualReviewy annualReviewy, BasicInformation basicInformation) {
        return annualReviewyMapper.selectAnnualReviewyListBySelf3(annualReviewy, basicInformation, SecurityUtils.getLoginUser()
                .getUsername());
    }


    /**
     * 新增feike
     *
     * @param map feike
     * @return 结果
     */
    @Override
    @Transactional
    //public int insertAnnualReviewy(AnnualReviewy annualReviewy)
    public int insertAnnualReviewy(Map<String, Object> map) {
        System.out.println("年审新增中的map==" + map);
        //String instanceId = IdUtils.get16UUID();
        ArrayList<ApprovalStatusReport> reports = new ArrayList<>();
        String processDefinitionKey = instanceIdUtil.getAbbreviationToMap((String) map.get("processDefinitionKey"));
        if(StringUtils.isEmpty(processDefinitionKey)){
             processDefinitionKey = instanceIdUtil.getAbbreviationToMap("annualVerification");
        }
        String currentVal = instanceIdUtil.getRedisInstanceId(processDefinitionKey);
        String instanceId = instanceIdUtil.getIstanceId(processDefinitionKey, currentVal);
        String title = "";
        if (StringUtils.isNotNull(map.get("name"))) {
            title =  String.valueOf(map.get("name"));
        } else {
            title = "Annual Review";
        }
        Task task = null;
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());
        if (map.get("caoGao") != null && map.get("caoGao").toString().equals("1")) {
            //草稿行为,不发流程，仅保存
        } else {
            //流程开始
            ProcessInstance processInstance = null;
            if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey(map.get("processDefinitionKey") + "")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            } else {
                processInstance = processRuntime.start(ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("annualVerification")
                        .withName(title)
                        .withBusinessKey(instanceId)
                        // .withVariable("deptLeader",join)
                        .build());
            }


            task = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .singleResult();



            TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
            List<Task> todoList = query.list();//获取申请人的待办任务列表
            for (Task tmp : todoList) {
                if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                    task = tmp;//获取当前流程实例，当前申请人的待办任务
                    break;
                }
            }
            HashMap<String, Object> variables = new HashMap<String, Object>();
            List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
            for (Map<String, Object> form : actForm) {
                variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
            }
            variables.put("toUnderwriter", 0);
            taskService.complete(task.getId(), variables);

        }
        //h_basic_information ============================================
        List<Map<String, Object>> dealernameList = (List<Map<String, Object>>) map.get("basicInformation");

        if (dealernameList != null && dealernameList.size() > 0) {
            Map<String, Object> groupNameMap = (Map<String, Object>) map.get("groupName");
            Map<String, Object> groupName = (Map<String, Object>) groupNameMap.get("groupName");
            for (Map<String, Object> stringObjectMap : dealernameList) {
                String gm = stringObjectMap.get("gm") != null ? "" + stringObjectMap.get("gm") : "";
                String dealerCodeFromManufacturer = stringObjectMap.get("dealerCodeFromManufacturer") != null ? "" + stringObjectMap.get("dealerCodeFromManufacturer") : "";
                String dealerCodeFromWFS = stringObjectMap.get("dealerCodeFromWFS") != null ? "" + stringObjectMap.get("dealerCodeFromWFS") : "";
                String dealerNameCN = stringObjectMap.get("dealerNameCN") != null ? "" + stringObjectMap.get("dealerNameCN") : "";
                String dealerNameEN = stringObjectMap.get("dealerNameEN") != null ? "" + stringObjectMap.get("dealerNameEN") : "";
                String dealername = stringObjectMap.get("dealername") != null ? "" + stringObjectMap.get("dealername") : "";
                String incorporationDate = stringObjectMap.get("incorporationDate") != null ? "" + stringObjectMap.get("incorporationDate") : "";
                String individualGuarantor = stringObjectMap.get("individualGuarantor") != null ? "" + stringObjectMap.get("individualGuarantor") : "";
                String joinSectorDealerNetworkDate = stringObjectMap.get("joinSectorDealerNetworkDate") != null ? "" + stringObjectMap.get("joinSectorDealerNetworkDate") : "";
                String paidupCapital = stringObjectMap.get("paidupCapital") != null ? "" + stringObjectMap.get("paidupCapital") : "";
                String province = stringObjectMap.get("province") != null ? "" + stringObjectMap.get("province") : "";


                Object registeredCapital = stringObjectMap.get("registeredCapital");
                Object registeredAddressCN = stringObjectMap.get("registeredAddressCN");
                Object registeredAddressEN = stringObjectMap.get("registeredAddressEN");
                Object legalRepresentativeCN = stringObjectMap.get("legalRepresentativeCN");
                Object legalRepresentativeEN = stringObjectMap.get("legalRepresentativeEN");



                String value = stringObjectMap.get("value") != null ? "" + stringObjectMap.get("value") : "";
                StringBuilder sector = new StringBuilder();
                Object sector1 = stringObjectMap.get("sector");
                if (sector1 != null) {
                    List sectorList = (List) sector1;//数组
                    if (sectorList != null && sectorList.size() > 0) {
                        for (int i = 0; i < sectorList.size(); i++) {
                            sector.append(sectorList.get(i));
                            sector.append(",");
                        }
                    }
                }

                if (!StringUtils.isEmpty(sector)) {
                    sector.deleteCharAt(sector.length() - 1);
                    System.out.println("sector" + sector);
                }
                // StringBuilder shareholdersAndShare=new StringBuilder();
                StringBuilder shareholders = new StringBuilder();

                Object shareholdersAndShare = stringObjectMap.get("shareholdersAndShare");
                if (shareholdersAndShare != null) {
                    List shareholdersAndShareList = (List) shareholdersAndShare;//数组
                    if (shareholdersAndShareList != null && shareholdersAndShareList.size() > 0) {
                        for (int i = 0; i < shareholdersAndShareList.size(); i++) {

                            StringBuilder shareholder = new StringBuilder();
                            Map<String, Object> stringObjectMap1 = (Map<String, Object>) shareholdersAndShareList.get(i);
                            String s1 = (String) stringObjectMap1.get("shareholdersCn");
                            String s2 = (String) stringObjectMap1.get("shareholdersEn");
                            String s3 = (String) stringObjectMap1.get("share");
                            shareholder.append(s1);
                            shareholder.append("$|");
                            shareholder.append(s2);
                            shareholder.append("$|");
                            shareholder.append(s3);
                            shareholders.append(shareholder);
                            shareholders.append("#");
                        }
                    }
                }
                if (!StringUtils.isEmpty(shareholders)) {
                    shareholders.deleteCharAt(shareholders.length() - 1);
                    System.out.println("shareholders" + shareholders);
                }
     /*           if (!StringUtils.isEmpty(share)) {
                    share.deleteCharAt(share.length() - 1);
                    System.out.println("share" + share);
                }*/

                BasicInformation basicInformation = new BasicInformation();
                Object relatedWorkingExperience = stringObjectMap.get("relatedWorkingExperience");
                if (relatedWorkingExperience != null) {
                    int relatedWorkingExperienceInt = (int) relatedWorkingExperience;
                    basicInformation.setRelatedWorkingExperience(relatedWorkingExperienceInt);
                }
                if (groupName != null && !(groupName.equals(" "))) {
                    basicInformation.setGroupNameCN((String) groupName.get("groupNameCN"));
                    basicInformation.setGroupNameEN((String) groupName.get("groupNameEN"));
                }
                basicInformation.setId(IdUtils.simpleUUID());
                if (!StringUtils.isEmpty(gm)) {
                    basicInformation.setGm(gm);
                }
                if (!StringUtils.isEmpty(dealerCodeFromManufacturer) && !("[]".equals(dealerCodeFromManufacturer))) {
                    basicInformation.setDealerCodeFromManufacturer(dealerCodeFromManufacturer);
                }
                if (!StringUtils.isEmpty(dealerCodeFromWFS)) {
                    basicInformation.setDealerCodeFromWFS(dealerCodeFromWFS.replace(" ", ""));
                }
                if (!StringUtils.isEmpty(dealerNameCN)) {
                    basicInformation.setDealerNameCN(dealerNameCN);
                }

                if (null != registeredAddressCN ) {
                    basicInformation.setRegisteredAddressCN(registeredAddressCN.toString());
                }
                if (null !=registeredAddressEN) {
                    basicInformation.setRegisteredAddressEN(registeredAddressEN.toString());
                }
                if (null !=legalRepresentativeCN) {
                    basicInformation.setLegalRepresentativeCN(legalRepresentativeCN.toString());
                    basicInformation.setOutLegalRepresentativeCN(legalRepresentativeCN.toString());
                }
                if (null !=registeredCapital) {
                    basicInformation.setRegisteredCapital(registeredCapital.toString());
                }

                if (null !=legalRepresentativeEN) {
                    basicInformation.setLegalRepresentativeEN(legalRepresentativeEN.toString());
                }
                if (!StringUtils.isEmpty(dealerNameEN)) {
                    basicInformation.setDealerNameEN(dealerNameEN);
                }

                if (!StringUtils.isEmpty(dealername)) {
                    basicInformation.setDealername(dealername);
                }
                if (!StringUtils.isEmpty(incorporationDate)) {
                    basicInformation.setIncorporationDate(incorporationDate);
                }
                if (!StringUtils.isEmpty(joinSectorDealerNetworkDate)) {
                    basicInformation.setJoinSectorDealerNetworkDate(joinSectorDealerNetworkDate);
                }
                if (!StringUtils.isEmpty(paidupCapital)) {
                    basicInformation.setPaidupCapital(paidupCapital);
                }
                if (!StringUtils.isEmpty(province)) {
                    basicInformation.setProvince(province);
                }

                if (!StringUtils.isEmpty(sector)) {
                    basicInformation.setSector(sector.toString());
                }
                if (!StringUtils.isEmpty(shareholders)) {
                    basicInformation.setShareholders(shareholders.toString());
                }
       /*         if (!StringUtils.isEmpty(share)) {
                    basicInformation.setShare(share.toString());
                }*/
                if (!StringUtils.isEmpty(value)) {
                    basicInformation.setDealerValue(value);
                }
                basicInformation.setInstanceId(instanceId);
                basicInformationMapper.insertBasicInformation(basicInformation);
                saveDbLog("1","新增流程","BASIC INFORMATION",instanceId,null,basicInformation,null);


            }
        }

        //TODO 没有传来
        //h_detail_information ============================================
        Object dealerBackground = map.get("dealer_background");
        if (dealerBackground != null) {
            List<DetailInformation> detailInformationList = (List<DetailInformation>) dealerBackground;
            System.out.println("detailInformationList==" + detailInformationList);
            String detailInformationLists = JSON.toJSONString(detailInformationList);
            detailInformationList = JSON.parseArray(detailInformationLists, DetailInformation.class);
            if (detailInformationList != null && detailInformationList.size() > 0) {
                for (DetailInformation detailInformation : detailInformationList) {
                    detailInformation.setDealerId(detailInformation.getId());
                    detailInformation.setId(IdUtils.simpleUUID());
                    detailInformation.setInstanceId(instanceId);
                    detailInformationMapper.insertDetailInformation(detailInformation);
                    saveDbLog("1","新增流程",null ,instanceId,null,detailInformation,null);
                }
            }
        }

        //————————————————————————————————————————————————————————————————————————————————————

        //TODO-已完成
        //h_sales_performance_and_target ============================================
        Object salesPerformanceAndTargetObj = map.get("sales_performance_and_target");
        if (salesPerformanceAndTargetObj != null) {
            List<Map<String, Object>> salesPerformanceAndTargetVOList = (List<Map<String, Object>>) salesPerformanceAndTargetObj;
            System.out.println("salesPerformanceAndTargetVOList==" + salesPerformanceAndTargetVOList);

            if (salesPerformanceAndTargetVOList != null && salesPerformanceAndTargetVOList.size() > 0) {
                for (Map<String, Object> mapone : salesPerformanceAndTargetVOList) {
                    //表格内容
                    List<Map<String, Object>> children = (List<Map<String, Object>>) mapone.get("children");
                    //表格头
                    Map<String, Object> title1 = (Map<String, Object>) mapone.get("title");
                    //取表格头动态部分
                    List<Map<String, Object>> second = (List<Map<String, Object>>) title1.get("second");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (Map<String, Object> secondhead : second) {
                        String title2 = secondhead.get("title").toString();
                        stringBuilder.append(title2).append(",");
                    }
                    String s = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                    for (Map<String, Object> maptwo : children) {
                        SalesPerformanceAndTarget salesPerformanceAndTarget = new SalesPerformanceAndTarget();
                        salesPerformanceAndTarget.setId(IdUtils.simpleUUID());
                        salesPerformanceAndTarget.setDealerId(maptwo.get("id").toString());
                        salesPerformanceAndTarget.setDealername(maptwo.get("dealerName").toString());
                        salesPerformanceAndTarget.setItem(maptwo.get("Item").toString());
                        salesPerformanceAndTarget.setSector(maptwo.get("Sector").toString());
                        if (!StringUtils.isEmpty(maptwo.get(second.get(0).get("title")).toString())) {
                            salesPerformanceAndTarget.setActual2021(Long.parseLong(maptwo.get(second.get(0).get("title")).toString()));
                        }
                        if (!StringUtils.isEmpty(maptwo.get(second.get(1).get("title")).toString())) {
                            salesPerformanceAndTarget.setActualYTD2022(Long.parseLong(maptwo.get(second.get(1).get("title")).toString()));
                        }

                        //TODO 这个动态列的值没有传过来
                        if(!StringUtils.isEmpty(maptwo.get("currentYear").toString())){
                            salesPerformanceAndTarget.setTarget2022(maptwo.get("currentYear").toString());
                        }

                        salesPerformanceAndTarget.setIndexId(maptwo.get("id").toString());
                        salesPerformanceAndTarget.setThead(s);
                        salesPerformanceAndTarget.setInstanceId(instanceId);
                        salesPerformanceAndTargetMapper.insertSalesPerformanceAndTarget(salesPerformanceAndTarget);
                        saveDbLog("1","新增流程","SALES PERFORMANCE AND TARGET (DATA FROM OEM)",instanceId,null,salesPerformanceAndTarget,null);

                    }
                }
            }
        }

        //TODO-已完成，------
        //h_limit_calculation_for_commerical_needs ============================================
        Object limitCalculationForCommericalNeedObj = map.get("limit_calculation_for_commerical_needs");
        if (limitCalculationForCommericalNeedObj != null) {
            List<Map<String, Object>> limitCalculationForCommericalNeeds = (List<Map<String, Object>>) limitCalculationForCommericalNeedObj;
            System.out.println("limitCalculationForCommericalNeeds==" + limitCalculationForCommericalNeeds);
            if (limitCalculationForCommericalNeeds != null && limitCalculationForCommericalNeeds.size() > 0) {
                for (Map<String, Object> limitCalculationForCommericalNeedVO : limitCalculationForCommericalNeeds) {
                    List<Map<String, Object>> limit_calculation_for_commerical_needs = (List<Map<String, Object>>) limitCalculationForCommericalNeedVO.get("limit_calculation_for_commerical_needs");

                    String stringObjectMap = (String) limitCalculationForCommericalNeedVO.get("dealerName");
                    for (Map<String, Object> aa : limit_calculation_for_commerical_needs) {
                        LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed = new LimitCalculationForCommericalNeeds();
                        limitCalculationForCommericalNeed.setId(IdUtils.simpleUUID());
                        limitCalculationForCommericalNeed.setDealername(stringObjectMap);
                        limitCalculationForCommericalNeed.setSector(aa.get("sector").toString());
                        limitCalculationForCommericalNeed.setModel(aa.get("model").toString());
                        if (StringUtils.isNotNull(aa.get("avgLoanAmt"))) {
                            limitCalculationForCommericalNeed.setAip(Long.parseLong(aa.get("avgLoanAmt").toString()));
                        }
                        if (StringUtils.isNotNull(aa.get("actualAvgDso"))) {
                            limitCalculationForCommericalNeed.setAtd(aa.get("actualAvgDso").toString());
                        }
                        if (StringUtils.isNotNull(aa.get("estimatedannualwholesaleunits"))) {
                            limitCalculationForCommericalNeed.setEstimatedannualwholesaleunits(aa.get("estimatedannualwholesaleunits").toString());
                        }
                        if (StringUtils.isNotNull(aa.get("creditlimitfornewvehicle"))) {
                            limitCalculationForCommericalNeed.setCreditlimitfornewvehicle(aa.get("creditlimitfornewvehicle").toString());
                        }
                        limitCalculationForCommericalNeed.setInstanceId(instanceId);
                        limitCalculationForCommericalNeedsMapper.insertLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
                        saveDbLog("1","新增流程","LIMIT CALCULATION FOR COMMERCIAL NEEDS",instanceId,null,limitCalculationForCommericalNeed,null);

                    }

                }
            }
        }

        //TODO-已完成，------
        //h_other_financing_resource ============================================
        Object otherFinancingResourceObj = map.get("other_financing_resource");
        if (otherFinancingResourceObj != null) {
            List<OtherFinancingResourceVO> otherFinancingResourceVOs = (List<OtherFinancingResourceVO>) otherFinancingResourceObj;
            System.out.println("otherFinancingResourceVOs==" + otherFinancingResourceVOs);
            String otherFinancingResourceVOss = JSONUtil.toJsonStr(otherFinancingResourceVOs);
            otherFinancingResourceVOs = JSONUtil.toList(otherFinancingResourceVOss, OtherFinancingResourceVO.class);
           // otherFinancingResourceVOs = JSON.parseArray(otherFinancingResourceVOss, OtherFinancingResourceVO.class);
            if (otherFinancingResourceVOs != null && otherFinancingResourceVOs.size() > 0) {
                for (OtherFinancingResourceVO otherFinancingResourceVO : otherFinancingResourceVOs) {
                    if(otherFinancingResourceVO.getId() == null || otherFinancingResourceVO.getId() ==""){
                        OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                        otherFinancingResource.setId(IdUtils.simpleUUID());
                        otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                        otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                        otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionName());
                        otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoanType());
                        otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedLimit());
                        otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                        otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                        otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestRate());
                        otherFinancingResource.setDueDate(otherFinancingResourceVO.getDueDate());
                        otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                        //otherFinancingResource.setInstanceId(instanceId);
                        otherFinancingResourceMapper.insertOtherFinancingResource(otherFinancingResource);
                        saveDbLog("1","新增流程","OTHER FINANCING RESOURCE",instanceId,null,otherFinancingResource,null);

                    }else{
                        OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                        otherFinancingResource.setId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                        otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                        otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionName());
                        otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoanType());
                        otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedLimit());
                        otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                        otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                        otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestRate());
                        otherFinancingResource.setDueDate(otherFinancingResourceVO.getDueDate());
                        otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                        //otherFinancingResource.setInstanceId(instanceId);
                        OtherFinancingResource otherFinancingResource1 = otherFinancingResourceMapper.selectOtherFinancingResourceById(otherFinancingResourceVO.getId());
                        otherFinancingResourceMapper.updateOtherFinancingResourceByid(otherFinancingResource);
                        saveDbLog("3","新增流程","OTHER FINANCING RESOURCE",instanceId,otherFinancingResource1,otherFinancingResource,null);
                    }
                }
            }
        }

        //TODO ,传来了
        //h_temporary_condition_follow_up ============================================
        // Object temporary_condition_follow_up = map.get("h_temporary_condition_follow_up");
        Object temporaryConditionFollowUpObj = map.get("temporary_condition_follow_up");
        if (temporaryConditionFollowUpObj != null) {
            List<TemporaryConditionFollowUp> temporaryConditionFollowUps = (List<TemporaryConditionFollowUp>) temporaryConditionFollowUpObj;
            System.out.println("temporaryConditionFollowUps==" + temporaryConditionFollowUps);
            String temporaryConditionFollowUpss = JSON.toJSONString(temporaryConditionFollowUps);
            temporaryConditionFollowUps = JSON.parseArray(temporaryConditionFollowUpss, TemporaryConditionFollowUp.class);
            if (temporaryConditionFollowUps != null && temporaryConditionFollowUps.size() > 0) {
                for (TemporaryConditionFollowUp temporaryConditionFollowUp : temporaryConditionFollowUps) {
                    if(temporaryConditionFollowUp.getId() ==null || temporaryConditionFollowUp.getId() ==""){
                        temporaryConditionFollowUp.setDealerId(temporaryConditionFollowUp.getId());
                        temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                        //temporaryConditionFollowUp.setInstanceId(instanceId);
                        temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
                        saveDbLog("1","新增流程","TEMPORARY CONDITION FOLLOW UP",instanceId,null,temporaryConditionFollowUp,null);
                    }else{
                        TemporaryConditionFollowUp temporaryConditionFollowUp1 = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpById(temporaryConditionFollowUp.getId());
                        temporaryConditionFollowUpMapper.updateTemporaryConditionFollowUp(temporaryConditionFollowUp);
                        saveDbLog("3","新增流程","TEMPORARY CONDITION FOLLOW UP",instanceId,temporaryConditionFollowUp1,temporaryConditionFollowUp,null);
                    }

                }
            }
        }

        //TODO 没有传来
        Object approved_limit_and_condition = map.get("approved_limit_and_condition");
        System.out.println("approved_limit_and_condition==" + approved_limit_and_condition);
        if (approved_limit_and_condition != null) {
            List<ApprovedLimitAndConditionVO> approvedLimitAndConditionVOs = (List<ApprovedLimitAndConditionVO>) approved_limit_and_condition;
            String s = JSON.toJSONString(approvedLimitAndConditionVOs);
            approvedLimitAndConditionVOs = JSON.parseArray(s, ApprovedLimitAndConditionVO.class);
            for (ApprovedLimitAndConditionVO approvedLimitAndConditionVO : approvedLimitAndConditionVOs) {
                ApprovedLimitAndCondition approvedLimitAndCondition = new ApprovedLimitAndCondition();
                BeanUtils.copyProperties(approvedLimitAndConditionVO, approvedLimitAndCondition);
                approvedLimitAndCondition.setId(IdUtils.simpleUUID());
                approvedLimitAndCondition.setDealerid(IdUtils.simpleUUID());
                approvedLimitAndCondition.setInstanceid(instanceId);

                DetailInformation detailInformation = new DetailInformation();
                detailInformation.setId(IdUtils.simpleUUID());
                detailInformation.setDealerId(IdUtils.simpleUUID());
                detailInformation.setDealername(approvedLimitAndConditionVO.getDealername());
                detailInformation.setMonth(approvedLimitAndConditionVO.getMonth());
                detailInformation.setLoyaltyGrade(approvedLimitAndConditionVO.getLoyaltyGrade());

                approvedLimitAndConditionMapper.insertApprovedLimitAndCondition(approvedLimitAndCondition);
               // saveDbLog("1","新增流程",instanceId,null,approvedLimitAndCondition);
                detailInformationMapper.insertDetailInformation(detailInformation);
               // saveDbLog("1","新增流程",instanceId,null,detailInformation);
            }
        }

        Object loyalty_performance_4q = map.get("loyalty_performance_4q");
        if (loyalty_performance_4q != null) {
            List<LoyaltyPerformance4q> loyaltyPerformance4qs = (List<LoyaltyPerformance4q>) loyalty_performance_4q;
            String s = JSON.toJSONString(loyaltyPerformance4qs);
            loyaltyPerformance4qs = JSON.parseArray(s, LoyaltyPerformance4q.class);
            for (LoyaltyPerformance4q loyaltyPerformance4q : loyaltyPerformance4qs) {
                loyaltyPerformance4q.setId(IdUtils.simpleUUID());
                loyaltyPerformance4q.setInstanceId(instanceId);
                loyaltyPerformance4qMapper.insertLoyaltyPerformance4q(loyaltyPerformance4q);
                saveDbLog("1","新增流程","LOYALTY PERFORMANCE (FOR RECENT 4 QUARTERS)",instanceId,null,loyaltyPerformance4q,null);
            }
        }

        Object loyalty_performance_6month = map.get("loyalty_performance_6month");
        if (loyalty_performance_6month != null) {
            List<LoyaltyPerformance6month> loyaltyPerformance6months = (List<LoyaltyPerformance6month>) loyalty_performance_6month;
            String s = JSON.toJSONString(loyaltyPerformance6months);
            loyaltyPerformance6months = JSON.parseArray(s, LoyaltyPerformance6month.class);
            for (LoyaltyPerformance6month loyaltyPerformance6month : loyaltyPerformance6months) {
                loyaltyPerformance6month.setId(IdUtils.simpleUUID());
                loyaltyPerformance6month.setInstanceId(instanceId);
                loyaltyPerformance6monthMapper.insertLoyaltyPerformance6month(loyaltyPerformance6month);
                saveDbLog("1","新增流程","LOYALTY PERFORMANCE (FOR RECENT 6 MONTHS)",instanceId,null,loyaltyPerformance6month,null);
            }
        }

        // 从第三方接口取数据已完成  TODO
        //h_proposal_by_commerical_and_marketing ============================================
        // Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing_evaluate");
        Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing");
        if (proposal_by_commerical_and_marketing != null) {

            // List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketings = (List<ProposalByCommericalAndMarketingVO>) proposal_by_commerical_and_marketing;
            String s = JSON.toJSONString(proposal_by_commerical_and_marketing);
            List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketings = JSON.parseArray(s, ProposalByCommericalAndMarketingVO.class);
            ArrayList<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS = new ArrayList<>();
            for (ProposalByCommericalAndMarketingVO proposalByCommericalAndMarketingVO : proposalByCommericalAndMarketings) {
                ArrayList<ThirdCreditInfoSimpleChild> childArrayList = new ArrayList<>();
                ThirdCreditInfoSimpleVO thirdCreditInfoSimpleVO = new ThirdCreditInfoSimpleVO();
                thirdCreditInfoSimpleVO.setDealerId(proposalByCommericalAndMarketingVO.getDealerCode());
                thirdCreditInfoSimpleVO.setDealerName(proposalByCommericalAndMarketingVO.getDealername());
                ThirdCreditInfoSimpleChild thirdCreditInfoSimpleChild = new ThirdCreditInfoSimpleChild();
                thirdCreditInfoSimpleChild.setDealerId(proposalByCommericalAndMarketingVO.getDealerCode());
                thirdCreditInfoSimpleChild.setDealerName(proposalByCommericalAndMarketingVO.getDealername());
                thirdCreditInfoSimpleChild.setSector(proposalByCommericalAndMarketingVO.getSector());
                thirdCreditInfoSimpleChild.setLimitType(proposalByCommericalAndMarketingVO.getLimitType());
                thirdCreditInfoSimpleChild.setExpiryDate(proposalByCommericalAndMarketingVO.getExpiryDate());
                childArrayList.add(thirdCreditInfoSimpleChild);
                thirdCreditInfoSimpleVO.setChild(childArrayList);
                thirdCreditInfoSimpleVOS.add(thirdCreditInfoSimpleVO);
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = new ProposalByCommericalAndMarketing();
                BeanUtils.copyProperties(proposalByCommericalAndMarketingVO, proposalByCommericalAndMarketing);

                proposalByCommericalAndMarketing.setId(IdUtils.simpleUUID());
                proposalByCommericalAndMarketing.setDealerId(proposalByCommericalAndMarketingVO.getId());
                proposalByCommericalAndMarketing.setInstanceId(instanceId);
                proposalByCommericalAndMarketingMapper.insertProposalByCommericalAndMarketing(proposalByCommericalAndMarketing);
                saveDbLog("1","新增流程","PROPOSAL BY COMMERCIAL & MARKETING",instanceId,null,proposalByCommericalAndMarketing,null);
            }
            creditConditionService.saveAuditCreditCondition(instanceId, thirdCreditInfoSimpleVOS ,"新增流程");
        }

        //从第三方接口取数据已完成
        //h_wholesale_performance_currently ============================================
        Object wholesalePerformanceCurrentObj = map.get("WholesalePerformanceCurrent");
        if (wholesalePerformanceCurrentObj != null) {
            List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlyList = (List<WholesalePerformanceCurrently>) wholesalePerformanceCurrentObj;
            System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
            String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
            wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceCurrently.class);
            if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                for (WholesalePerformanceCurrently wholesalePerformanceCurrently : wholesalePerformanceCurrentlyList) {
                    wholesalePerformanceCurrently.setId(IdUtils.simpleUUID());
                    wholesalePerformanceCurrently.setDealerId(IdUtils.simpleUUID());
                    wholesalePerformanceCurrently.setInstanceId(instanceId);
                    wholesalePerformanceCurrentlyMapper.insertWholesalePerformanceCurrently(wholesalePerformanceCurrently);
                    saveDbLog("1","新增流程","WHOLESALE PERFORMANCE-CURRENTLY",instanceId,null,wholesalePerformanceCurrently,null);
                }
            }
        }

        //h_grade ============================================
        Object gradeObj = map.get("grade");
        if (gradeObj != null) {
            List<Grade> gradeList = (List<Grade>) gradeObj;
            System.out.println("gradeList==" + gradeList);
            String gradeStr = JSON.toJSONString(gradeList);
            gradeList = JSON.parseArray(gradeStr, Grade.class);
            if (gradeList != null && gradeList.size() > 0) {
                for (Grade grade : gradeList) {
                    grade.setId(IdUtils.simpleUUID());
                    grade.setInstanceId(instanceId);
                    gradeService.insertGrade(grade);
                    saveDbLog("1","新增流程","CRIXP GRADE",instanceId,null,grade,null);
                }
            }
        }

        //从第三方接口取数据已完成
        ////wholesale_performance_recent_three_months_os ============================================
        Object WholesalePerformanceOS = map.get("wholesalePerformanceOS");
        if (WholesalePerformanceOS != null) {
            Map<String, Object> wholesalePerformanceRecentThreeMonthsOsObj = (Map<String, Object>) WholesalePerformanceOS;
            if (wholesalePerformanceRecentThreeMonthsOsObj != null) {
                Object result = wholesalePerformanceRecentThreeMonthsOsObj.get("row");
                List<String> titleObj = (List<String>) wholesalePerformanceRecentThreeMonthsOsObj.get("title");
                String value = null;
                if (titleObj != null) {
                    value = Joiner.on(",").join(titleObj);
                }
//                String lastLastYearMonth = "";
//                String lastYearMonth = "";
//                String currentYearMonth = "";
//                if (titleObj != null) {
//                    List list = (List) titleObj;
//                    lastLastYearMonth = "" + list.get(2);
//                    lastYearMonth = "" + list.get(3);
//                    currentYearMonth = "" + list.get(4);
//                }
                if (result != null) {
                    List<Map<String, Object>> wholesalePerformanceCurrentlyList = (List<Map<String, Object>>) result;
                    System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
                    // String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
                    // wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceRecentThreeMonths.class);
                    if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                        for (Map<String, Object> stringObjectMap : wholesalePerformanceCurrentlyList) {
                            WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonths = new WholesalePerformanceRecentThreeMonths();
                            wholesalePerformanceRecentThreeMonths.setId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setDealerId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setInstanceId(instanceId);
                            wholesalePerformanceRecentThreeMonths.setType("OS");
                            if (!StringUtils.isEmpty(stringObjectMap.get(titleObj.get(2)).toString())) {
                                wholesalePerformanceRecentThreeMonths.setLastLastYearMonth(new BigDecimal(stringObjectMap.get(titleObj.get(2)).toString()).toString());
                            }
                            if (!StringUtils.isEmpty(stringObjectMap.get(titleObj.get(3)).toString())) {
                                wholesalePerformanceRecentThreeMonths.setLastYearMonth(new BigDecimal(stringObjectMap.get(titleObj.get(3)).toString()).toString());
                            }
                            if (!StringUtils.isEmpty(stringObjectMap.get(titleObj.get(4)).toString())) {
                                wholesalePerformanceRecentThreeMonths.setCurrentYearMonth(new BigDecimal(stringObjectMap.get(titleObj.get(4)).toString()).toString());
                            }
                            wholesalePerformanceRecentThreeMonths.setDEALER(stringObjectMap.get("Dealer").toString());
                            wholesalePerformanceRecentThreeMonths.setBRAND(stringObjectMap.get("Sector").toString());
                            wholesalePerformanceRecentThreeMonths.setThead(value);
                            wholesalePerformanceRecentThreeMonthsMapper.insertWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonths);
                            saveDbLog("1","新增流程","WHOLESALE PERFORMANCE-RECENT 3 MONTHS OS",instanceId,null,wholesalePerformanceRecentThreeMonths,null);
                        }
                    }
                }
            }
        }

        //从第三方接口取数据已完成,TODO 待确定数据存那张表中
        //wholesale_performance_recent_three_months ============================================
        Object wholesalePerformanceRecentThreeMonthsOs = map.get("WholesalePerformanceDSO");
        if (wholesalePerformanceRecentThreeMonthsOs != null) {
            Map<String, Object> wholesalePerformanceRecentThreeMonthsOsObj = (Map<String, Object>) wholesalePerformanceRecentThreeMonthsOs;
            if (wholesalePerformanceRecentThreeMonthsOsObj != null) {
                Object result = wholesalePerformanceRecentThreeMonthsOsObj.get("result");
                Object titleObj = wholesalePerformanceRecentThreeMonthsOsObj.get("title");
                String lastLastYearMonth = "";
                String lastYearMonth = "";
                String currentYearMonth = "";
                if (titleObj != null) {
                    List list = (List) titleObj;
                    lastLastYearMonth = "" + list.get(2);
                    lastYearMonth = "" + list.get(3);
                    currentYearMonth = "" + list.get(4);
                }
                if (result != null) {
                    List<Map<String, String>> wholesalePerformanceCurrentlyList = (List<Map<String, String>>) result;
                    System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
                    // String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
                    // wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceRecentThreeMonths.class);
                    if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                        for (Map<String, String> stringObjectMap : wholesalePerformanceCurrentlyList) {
                            WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonths = new WholesalePerformanceRecentThreeMonths();
                            wholesalePerformanceRecentThreeMonths.setId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setDealerId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setInstanceId(instanceId);
                            wholesalePerformanceRecentThreeMonths.setType("DSO");
                            wholesalePerformanceRecentThreeMonths.setLastLastYearMonth(stringObjectMap.get("lastLastYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setLastYearMonth(stringObjectMap.get("lastYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setCurrentYearMonth(stringObjectMap.get("currentYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setDEALER(stringObjectMap.get("DEALER"));
                            wholesalePerformanceRecentThreeMonths.setBRAND(stringObjectMap.get("BRAND"));
                            wholesalePerformanceRecentThreeMonthsMapper.insertWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonths);
                            saveDbLog("1","新增流程","WHOLESALE PERFORMANCE-RECENT 3 MONTHS DSO",instanceId,null,wholesalePerformanceRecentThreeMonths,null);
                        }
                    }
                }
            }
        }

        //从第三方接口取数据已完成,TODO 待确定数据存那张表中
        //wholesale_performance_recent_three_months ============================================
        Object wholesalePerformanceAgingObj = map.get("WholesalePerformanceAging");
        if (wholesalePerformanceAgingObj != null) {
            Map<String, Object> wholesalePerformanceRecentThreeMonthsOsObj = (Map<String, Object>) wholesalePerformanceAgingObj;
            if (wholesalePerformanceRecentThreeMonthsOsObj != null) {
                Object result = wholesalePerformanceRecentThreeMonthsOsObj.get("result");
                Object titleObj = wholesalePerformanceRecentThreeMonthsOsObj.get("title");
                String lastLastYearMonth = "";
                String lastYearMonth = "";
                String currentYearMonth = "";
                if (titleObj != null) {
                    List list = (List) titleObj;
                    lastLastYearMonth = "" + list.get(2);
                    lastYearMonth = "" + list.get(3);
                    currentYearMonth = "" + list.get(4);
                }
                if (result != null) {
                    List<Map<String, String>> wholesalePerformanceCurrentlyList = (List<Map<String, String>>) result;
                    System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
                    // String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
                    // wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceRecentThreeMonths.class);
                    if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                        for (Map<String, String> stringObjectMap : wholesalePerformanceCurrentlyList) {
                            WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonths = new WholesalePerformanceRecentThreeMonths();
                            wholesalePerformanceRecentThreeMonths.setId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setDealerId(IdUtils.simpleUUID());
                            wholesalePerformanceRecentThreeMonths.setInstanceId(instanceId);
                            wholesalePerformanceRecentThreeMonths.setType("Aging");
                            wholesalePerformanceRecentThreeMonths.setLastLastYearMonth(stringObjectMap.get("lastLastYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setLastYearMonth(stringObjectMap.get("lastYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setCurrentYearMonth(stringObjectMap.get("currentYearMonth"));
                            wholesalePerformanceRecentThreeMonths.setDEALER(stringObjectMap.get("DEALER"));
                            wholesalePerformanceRecentThreeMonths.setBRAND(stringObjectMap.get("BRAND"));
                            wholesalePerformanceRecentThreeMonthsMapper.insertWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonths);
                            saveDbLog("1","新增流程","WHOLESALE PERFORMANCE-RECENT 3 MONTHS AGING",instanceId,null,wholesalePerformanceRecentThreeMonths,null);
                        }
                    }
                }
            }
        }


/*        if (map.get("creditCondition") != null) {
            String creditListString = JSON.toJSONString(map.get("creditCondition"));
            List<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS = JSON.parseArray(creditListString, ThirdCreditInfoSimpleVO.class);
            //ThirdCreditInfoSimpleVO creditInfoSimpleVO = MapUtil.get(map, "creditCondition", ThirdCreditInfoSimpleVO.class);
            creditConditionService.saveAuditCreditCondition(instanceId, thirdCreditInfoSimpleVOS);
        }*/


        //TODO 没有传来
        //h_wholesale_performance_recent_three_months ============================================
        String wholesale_performance_recent_three_months = (String) map.get("wholesale_performance_recent_three_months");
        if (!StringUtils.isEmpty(wholesale_performance_recent_three_months)) {
            List<WholesalePerformanceRecentThreeMonths> wholesalePerformanceRecentThreeMonths = JSON.parseArray(wholesale_performance_recent_three_months, WholesalePerformanceRecentThreeMonths.class);
            for (WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonth : wholesalePerformanceRecentThreeMonths) {
                wholesalePerformanceRecentThreeMonth.setId(IdUtils.simpleUUID());
                wholesalePerformanceRecentThreeMonth.setDealerId(IdUtils.simpleUUID());
                wholesalePerformanceRecentThreeMonth.setInstanceId(instanceId);
                wholesalePerformanceRecentThreeMonthsMapper.insertWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonth);
                saveDbLog("1","新增流程","WHOLESALE PERFORMANCE-RECENT 3 MONTHS AGING",instanceId,null,wholesalePerformanceRecentThreeMonth,null);
            }
        }

        //h_securities ============================================
        String securitiesList = JSON.toJSONString(map.get("securities"));
        System.out.println("securitiesList==" + securitiesList);
        if (!StringUtils.isEmpty(securitiesList)) {
            List<SecuritieVO> securitiesLists = JSON.parseArray(securitiesList, SecuritieVO.class);
            if (securitiesLists != null && securitiesLists.size() > 0) {
                for (SecuritieVO securitieVO : securitiesLists) {
                    List<Securities> children = securitieVO.getChildren();
                    if (null != children && children.size() > 0) {
                        for (Securities child : children) {
                            child.setDealername(securitieVO.getDealername());
                            child.setId(IdUtils.simpleUUID());
                            child.setInstanceId(instanceId);
                            if(!StringUtils.isEmpty(child.getProposalNameCN())){
                                child.setProposalNameCN(child.getProposalNameCN());
                            }else{
                                child.setProposalNameCN(null);
                            }
                            if(!StringUtils.isEmpty(child.getProposalNameEN())){
                                child.setProposalNameEN(child.getProposalNameEN());
                            }else{
                                child.setProposalNameEN(null);
                            }

                            securitiesMapper.insertSecurities(child);
                            saveDbLog("1","新增流程","GUARANTEE INFORMATION",instanceId,null,child,null);
                        }
                    }
                }
            }
        }



        //active_limit_adjustment_proposal数据项插入
        Object activeLimitAdjustmentProposal = map.get("active_limit_adjustment_proposal");
        if (activeLimitAdjustmentProposal != null) {
            List<Map<String, String>> proposalLists = (List<Map<String, String>>) activeLimitAdjustmentProposal;
            if (proposalLists != null && proposalLists.size() > 0) {
                for (Map proposal : proposalLists) {
                    ActiveLimitAdjustmentProposal adjustmentProposal = new ActiveLimitAdjustmentProposal();
                    adjustmentProposal.setId(IdUtils.simpleUUID());
                    adjustmentProposal.setInstanceId(instanceId);
                    adjustmentProposal.setDealerName(String.valueOf(proposal.get("dealerName")));
                    adjustmentProposal.setSector(String.valueOf(proposal.get("sector")));
                    if(proposal.get("deposit")!=null){
                        if(!StringUtils.isEmpty(String.valueOf(proposal.get("deposit")))){
                            adjustmentProposal.setDeposit(String.valueOf(proposal.get("deposit")));
                        }else{
                            adjustmentProposal.setDeposit("");
                        }
                    }else{
                        adjustmentProposal.setDeposit("");
                    }

                    adjustmentProposal.setLimitType(String.valueOf(proposal.get("LimitType")));
                    adjustmentProposal.setActiveLimit(Long.valueOf(String.valueOf(proposal.get("activeLimit"))));
                    adjustmentProposal.setCreditLimit(Long.valueOf(String.valueOf(proposal.get("CreditLimit"))));
                    adjustmentProposal.setActiveLimit(Long.valueOf(String.valueOf(proposal.get("ActiveLimit"))));
                    String approvedCashDeposit = String.valueOf(proposal.get("approvedCashDeposit"));
                    if (approvedCashDeposit == null || "".equals(approvedCashDeposit)) {
                        approvedCashDeposit = "0";
                    }
                    adjustmentProposal.setCurrentCashDeposit(approvedCashDeposit);
                    adjustmentProposal.setActiveOS(new BigDecimal(String.valueOf(proposal.get("ActiveOS"))));
                    if(StringUtils.isEmpty(proposal.get("proposedActiveLimit").toString())){
                        adjustmentProposal.setProposedActiveLimit(String.valueOf(proposal.get("ActiveLimit")));
                    }else{
                        adjustmentProposal.setProposedActiveLimit(String.valueOf(proposal.get("proposedActiveLimit")));
                    }

                    adjustmentProposal.setDealerCode(String.valueOf(proposal.get("dealerCode")));
                    adjustmentProposal.setActiveLimitChange(String.valueOf(proposal.get("activeLimitChange")));
                    adjustmentProposal.setCurrentDeposit(String.valueOf(proposal.get("currentDeposit")));
                    activeLimitAdjustmentProposalMapper.insertActiveLimitAdjustmentProposal(adjustmentProposal);
                    saveDbLog("1","新增流程","ACTIVE LIMIT ADJUSTMENT PROPOSAL",instanceId,null,adjustmentProposal,null);
                }
            }
        }
        //插入cbFleetDetails
        Object cbFleetDetail = map.get("cb_fleet_details");
        if (cbFleetDetail != null) {
            List<CbFleetDetails> cbFleetDetailList = JSON.parseArray(JSON.toJSONString(cbFleetDetail), CbFleetDetails.class);
            if (cbFleetDetailList != null && cbFleetDetailList.size() > 0) {
                for (CbFleetDetails fleet : cbFleetDetailList) {
                    fleet.setId(IdUtils.simpleUUID());
                    fleet.setInstanceId(instanceId);
                    cbFleetDetailsMapper.insertCbFleetDetails(fleet);
                    saveDbLog("1","新增流程","CB Fleet Details",instanceId,null,fleet,null);
                }
            }
        }
//        mortgageAmount   interest
        Object balanceInfo = map.get("balance_information");
        if (balanceInfo != null) {
            List<BalanceInformation> balanceInfoList = JSON.parseArray(JSON.toJSONString(balanceInfo), BalanceInformation.class);
            if (balanceInfoList != null && balanceInfoList.size() > 0) {
                for (BalanceInformation balanceInformation : balanceInfoList) {
                    balanceInformation.setId(IdUtils.simpleUUID());
                    balanceInformation.setInstanceId(instanceId);
                    balanceInformationMapper.insertBalanceInformation(balanceInformation);
                    saveDbLog("1","新增流程","Balance Information",instanceId,null,balanceInformation,null);
                }
            }

        }

        if(!StringUtils.isEmpty(instanceId) && (instanceId.contains("NA") || title.equals("Annual Review"))){
            //生成新的
            List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceIdGroupName(instanceId);
            if(securities!=null && securities.size()>0){
                for (Securities security : securities) {
                    List<Securities> securities1 = securitiesMapper.selectSecuritiesByInstanceIdAndName2(instanceId, security.getDealername());
                    if(securities1!=null && securities1.size()>0){
                        for (Securities securities2 : securities1) {
                            if(securities2.getGuaranteeType()!=null && securities2.getGuaranteeType().equals("corporate")){
                                HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                                hBasicCorporateGuaranteeNew.setDealername(securities2.getDealername());
                                hBasicCorporateGuaranteeNew.setProposalNameCN(securities2.getProposalNameCN());
                                hBasicCorporateGuaranteeNew.setInstanceid(instanceId);

                                //查询在dealer info 是否存在
                                List<DealerInformation> dealerInformationsHistory = dealerInformationMapper.selectDealerInformationByDealerName(securities2.getDealername());
                                if(dealerInformationsHistory!=null && dealerInformationsHistory.size()>0 ){
                                    if(dealerInformationsHistory.get(0).getCorporateGuarantorJson()!=null){
                                        String corporateGuarantorJson = dealerInformationsHistory.get(0).getCorporateGuarantorJson();
                                        if(StringUtils.isNotEmpty(corporateGuarantorJson)){
                                            String[] CorporateGuarantor = corporateGuarantorJson.split(";");
                                            for(String co: CorporateGuarantor){
                                                Map<String, Object> CorporateGuarantorJsonMap = new HashMap<>();
                                                String[] CorporateGuarantorStr = co.split("#");
                                                if(CorporateGuarantorStr!=null){
                                                    int length = CorporateGuarantorStr.length;
                                                    if(length ==4){
                                                        String proposalNameCN = CorporateGuarantorStr[0];
                                                        if(proposalNameCN.equals(securities2.getProposalNameCN())){
                                                            hBasicCorporateGuaranteeNew.setGuarantorindustry(CorporateGuarantorStr[1]);
                                                            hBasicCorporateGuaranteeNew.setGuarantorregioncode(CorporateGuarantorStr[2]);
                                                            hBasicCorporateGuaranteeNew.setGuarantorscale(CorporateGuarantorStr[3]);
                                                        }
                                                    }

                                                    }
                                                }
                                            }
                                        }

                                }
                                basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                            }
                        }
                    }else{
                        HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                        hBasicCorporateGuaranteeNew.setDealername(security.getDealername());
                        hBasicCorporateGuaranteeNew.setProposalNameCN("-");
                        hBasicCorporateGuaranteeNew.setInstanceid(instanceId);
                        hBasicCorporateGuaranteeNew.setGuarantorscale("-");
                        hBasicCorporateGuaranteeNew.setGuarantorregioncode("-");
                        hBasicCorporateGuaranteeNew.setGuarantorindustry("-");
                        basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                    }
                }
            }else{
                List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByDealerName(instanceId);
                for (BasicInformation basicInformation : basicInformations) {
                    HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                    hBasicCorporateGuaranteeNew.setDealername(basicInformation.getDealerNameCN());
                    hBasicCorporateGuaranteeNew.setProposalNameCN("-");
                    hBasicCorporateGuaranteeNew.setInstanceid(instanceId);
                    hBasicCorporateGuaranteeNew.setGuarantorscale("-");
                    hBasicCorporateGuaranteeNew.setGuarantorregioncode("-");
                    hBasicCorporateGuaranteeNew.setGuarantorindustry("-");
                    basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                }
            }
            //还需要生成担保公司信息
            HBasicCorporate hBasicCorporate2 = new HBasicCorporate();
            hBasicCorporate2.setInstanceid(instanceId);
            List<HBasicCorporate> hBasicCorporates1 = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate2);
            if(hBasicCorporates1 == null || hBasicCorporates1.size() ==0 ){
                List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByDealerName(instanceId);
                for (BasicInformation basicInformation : basicInformations) {
                    HBasicCorporate hBasicCorporate = new HBasicCorporate();
                    hBasicCorporate.setDealername(basicInformation.getDealerNameCN());
                    hBasicCorporate.setInstanceid(instanceId);

                    List<DealerInformation> dealer = dealerInformationMapper.selectDealerInformationByDealerName(basicInformation.getDealerNameCN());
                    if(dealer!=null && dealer.size()>0){
                        if(dealer.get(0).getProvince()!=null){
                            hBasicCorporate.setProvince(dealer.get(0).getProvince());
                        }
                        if(dealer.get(0).getCity()!=null){
                            hBasicCorporate.setCity(dealer.get(0).getCity());
                        }
                        if(dealer.get(0).getPeopleSum()!=null){
                            hBasicCorporate.setPeoplesum(dealer.get(0).getPeopleSum());
                        }
                        if(dealer.get(0).getEnterpriseType()!=null){
                            hBasicCorporate.setEnterprisetype(dealer.get(0).getEnterpriseType());
                        }
                        if(dealer.get(0).getDownLoanAccount()!=null){
                            hBasicCorporate.setDownloanaccount(dealer.get(0).getDownLoanAccount());
                        }
                    }
                    basicCorporateMapper.insertHBasicCorporate(hBasicCorporate);
                }
            }
        }

/*        //这里写AML
        List<BasicInformation> basicInformations1 = basicInformationMapper.selectDealerGroupByDealerName(instanceId);
        for (BasicInformation basicInformation : basicInformations1) {
            List<HAml> amlList = createAmlList(instanceId,basicInformation.getDealerNameCN());
            for (HAml hAml : amlList) {
                //查询职位
                List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByDealerName(hAml.getDealerName());
                DealerInformation dealerInformation = dealerInformations.get(0);

                //查该经销商下对应得担保人和担保机构
                Securities securities = new Securities();
                securities.setInstanceId(instanceId);
                securities.setDealername(hAml.getDealerName());
                List<Securities> securitiesList1 = securitiesMapper.selectSecuritiesList(securities);
                StringBuilder stringBuilder = new StringBuilder();
                StringBuilder stringBuilder1 = new StringBuilder();
                for(Securities se: securitiesList1){
                    if(StringUtils.isNotEmpty(se.getGuaranteeType())){
                        if(se.getGuaranteeType().equals("personal")){
                            if(!StringUtils.isEmpty(se.getProposalNameCN())){
                                stringBuilder.append(se.getProposalNameCN()).append(",");
                            }
                        }
                        if(se.getGuaranteeType().equals("corporate")){
                            if(!StringUtils.isEmpty(se.getProposalNameCN())){
                                stringBuilder1.append(se.getProposalNameCN()).append(",");
                            }
                        }
                    }
                }

                if(hAml.getPosition().equals("法人")){
                    hAml.setName(dealerInformation.getLegalRepresentativeCN());
                }else if (hAml.getPosition().equals("股东")){
                    if(StringUtils.isNotEmpty(dealerInformation.getShareholderStructure())){
                        StringBuffer buffer = new StringBuffer();
                        String shareholderStructure = dealerInformation.getShareholderStructure();
                        String[] split = shareholderStructure.split(";");
                        for(String sp: split){
                            Map<String, Object> objectObjectHashMap = new HashMap<>();
                            ArrayList<String> objects = new ArrayList<>();
                            StringTokenizer stringTokenizer = new StringTokenizer(sp, "#:");
                            while(stringTokenizer.hasMoreElements()){
                                objects.add(stringTokenizer.nextToken());
                            }
                            if(objects.size()==3) {
                                buffer.append(objects.get(1)).append(",");
                            }
                        }
                        if(StringUtils.isNotEmpty(buffer)) {
                            String gd = (buffer.substring(0, buffer.length() - 1)).toString();
                            hAml.setName(gd);
                        }
                    }
                }else if (hAml.getPosition().equals("总经理")){
                    hAml.setName(dealerInformation.getGm());
                }else if (hAml.getPosition().equals("担保人")){
                    if(StringUtils.isNotEmpty(stringBuilder)) {
                        String danbaoren = (stringBuilder.substring(0, stringBuilder.length() - 1)).toString();
                        hAml.setName(danbaoren);
                    }
                }else if (hAml.getPosition().equals("担保公司")){
                    if(StringUtils.isNotEmpty(stringBuilder1)) {
                        String danbaojigou = (stringBuilder1.substring(0, stringBuilder1.length() - 1)).toString();
                        hAml.setName(danbaojigou);
                    }
                }
                //插入
                amlMapper.insertHAml(hAml);
            }
        }*/


        //h_notes ============================================
        Notes notes = new Notes();
        //String notesId = UUID.randomUUID().toString().replace("-", "");
        notes.setId(IdUtils.simpleUUID());
        notes.setInstanceId(instanceId);
        notes.setBasicNotes((String) map.get("basicNotes"));
        notes.setDealerNotes((String) map.get("dealerNotes"));
        notes.setLoyaltyNotes((String) map.get("loyaltyNotes"));
        notes.setAuditNotes((String) map.get("auditNotes"));
        notes.setWholesaleNotes((String) map.get("wholesaleNotes"));
        notes.setProposalNotes((String) map.get("proposalNotes"));
        notes.setGuaranteeNotes((String) map.get("guaranteeNotes"));
        notes.setAmlNotes((String) map.get("amlNotes"));
        notes.setComments((String) map.get("comments"));
        notes.setConditionNotes((String) map.get("conditionNotes"));

        notesMapper.insertNotes(notes);
        saveDbLog("1","新增流程","Notes",instanceId,null,notes,null);

        List<Map> applications = (List<Map>) map.get("application");
        System.out.println("applications==" + applications);
        if (applications != null && applications.size() > 0) {
            for (Map fileuploadVO : applications) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("application");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        List<Map> informations = (List<Map>) map.get("information");
        System.out.println("informations==" + informations);
        if (informations != null && informations.size() > 0) {
            for (Map fileuploadVO : informations) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("information");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        List<Map> financialss = (List<Map>) map.get("financials");
        System.out.println("financialss==" + financialss);
        if (financialss != null && financialss.size() > 0) {
            for (Map fileuploadVO : financialss) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("financials");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        List<Map> guarantees = (List<Map>) map.get("guarantee");
        System.out.println("guarantees==" + guarantees);
        if (guarantees != null && guarantees.size() > 0) {
            for (Map fileuploadVO : guarantees) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("guarantee");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        List<Map> corporates = (List<Map>) map.get("corporate");
        System.out.println("corporates==" + corporates);
        if (corporates != null && corporates.size() > 0) {
            for (Map fileuploadVO : corporates) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("corporate");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        List<Map> others = (List<Map>) map.get("other");
        System.out.println("others==" + others);
        if (others != null && others.size() > 0) {
            for (Map fileuploadVO : others) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("other");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }

        Object opDocument = map.get("opDocument");
        if (opDocument != null) {
            List<Map> opDocuments = (List<Map>) opDocument;
            for (Map fileuploadVO : opDocuments) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("opDocument");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }
        Object opDocumentFax = map.get("opDocumentFax");
        if (opDocumentFax != null) {
            List<Map> opDocumentFaxs = (List<Map>) opDocumentFax;
            for (Map fileuploadVO : opDocumentFaxs) {
                if(fileuploadVO.get("fileName")!=null){
                    Fileupload fileupload = new Fileupload();
                    fileupload.setFileName(fileuploadVO.get("fileName").toString());
                    fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                    fileupload.setUrl(fileuploadVO.get("url").toString());
                    fileupload.setId(IdUtils.simpleUUID());
                    fileupload.setInstanceId(instanceId);
                    fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                    fileupload.setCreateName(SecurityUtils.getNickName());
                    fileupload.setCreateTime(new Date());
                    fileupload.setType("opDocumentFax");
                    fileuploadService.insertFileupload(fileupload);
                    saveDbLog("1","新增流程","File Upload",instanceId,null,fileupload,null);
                }
            }
        }


        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(IdUtils.simpleUUID());
        annualReviewy.setTitle(title);
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setUpdateTime(DateUtils.getNowDate());
        annualReviewy.setInstanceId(instanceId);
        annualReviewy.setState("0");
        if (map.get("caoGao") != null && map.get("caoGao").toString().equals("1")) {//草稿行为时
            annualReviewy.setState("3");
        }
        if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
            annualReviewy.setType(map.get("processDefinitionKey") + "");
        } else {
            annualReviewy.setType("annualVerification");
        }

        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        Date nowDate = DateUtils.getNowDate();
        annualReviewy.setCreateTime(nowDate);
        if(ObjectUtil.isNotEmpty(task)){
            annualReviewy.setStartNode(task.getName());
        }
        //在这里插入报表
        ProposalByCommericalAndMarketing proposalByCommericalAndMarketingTemp1 = new ProposalByCommericalAndMarketing();
        proposalByCommericalAndMarketingTemp1.setInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingsByName = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupbyTwo(proposalByCommericalAndMarketingTemp1);
        for (ProposalByCommericalAndMarketing proposalByCommericalAndMarketing : proposalByCommericalAndMarketingsByName) {
            //一个经销商一条
            ProposalByCommericalAndMarketing proposalByCommericalAndMarketingTemp = new ProposalByCommericalAndMarketing();
            proposalByCommericalAndMarketingTemp.setInstanceId(instanceId);
            ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
            approvalStatusReport.setInstanceId(instanceId);
            approvalStatusReport.setDealerNameCn(proposalByCommericalAndMarketing.getDealername());
            DealerInformation dealerInformation = new DealerInformation();
            dealerInformation.setDealerName(proposalByCommericalAndMarketing.getDealername());
            dealerInformation.setMake(proposalByCommericalAndMarketing.getSector());
            List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
            String enName = dealerInformations.get(0).getEnName() == null ? " " : dealerInformations.get(0).getEnName();
            String group = dealerInformations.get(0).getGroupName() == null ? " " : dealerInformations.get(0).getGroupName();
            approvalStatusReport.setDealerNameEn(enName);
            approvalStatusReport.setGroup(group);


            //其他信息用/分开
            StringBuilder sectorStr = new StringBuilder();
            StringBuilder dealerCodeStr = new StringBuilder();
            StringBuilder expiryDateStr = new StringBuilder();
            StringBuilder depositStr = new StringBuilder();
            StringBuilder depositStr1 = new StringBuilder();
            proposalByCommericalAndMarketingTemp.setDealername(proposalByCommericalAndMarketing.getDealername());
            List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList5(proposalByCommericalAndMarketingTemp);

            List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings1 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketingTemp);
            Long currentLimitSum = 0l;
            Long proposedLimitSum = 0l;
            if(proposalByCommericalAndMarketings1!=null && proposalByCommericalAndMarketings1.size()>0){
                for (ProposalByCommericalAndMarketing byCommericalAndMarketing : proposalByCommericalAndMarketings1) {
                    if(byCommericalAndMarketing.getApprovedLimit()!=null){
                        currentLimitSum = currentLimitSum+byCommericalAndMarketing.getApprovedLimit();
                    }
                    if(byCommericalAndMarketing.getProposalLimit()!=null){
                        proposedLimitSum =proposedLimitSum+byCommericalAndMarketing.getProposalLimit();
                    }
                }
                approvalStatusReport.setOriginalLimit(currentLimitSum.toString());
                //approvalStatusReport.setUpdatedLimit(proposedLimitSum.toString());
            }

            for (ProposalByCommericalAndMarketing byCommericalAndMarketing : proposalByCommericalAndMarketings) {
                sectorStr.append(byCommericalAndMarketing.getSector()).append("/");
                dealerCodeStr.append(byCommericalAndMarketing.getDealerCode()).append("/");
                proposalByCommericalAndMarketingTemp.setSector(byCommericalAndMarketing.getSector());
                List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings2 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList1(proposalByCommericalAndMarketingTemp);

                if(proposalByCommericalAndMarketings2!=null && proposalByCommericalAndMarketings2.size()>0){
                    StringBuilder deposit = new StringBuilder();
                    StringBuilder deposit2 = new StringBuilder();
                    for (ProposalByCommericalAndMarketing byCommericalAndMarketing1 : proposalByCommericalAndMarketings2) {
                        if(!StringUtils.isEmpty(byCommericalAndMarketing1.getApprovedCashDeposit())){
                            deposit.append(byCommericalAndMarketing1.getApprovedCashDeposit()).append(",");
                        }
                        if(!StringUtils.isEmpty(byCommericalAndMarketing1.getProposalCashDeposit())){
                            deposit2.append(byCommericalAndMarketing1.getProposalCashDeposit()).append(",");
                        }
                        if(byCommericalAndMarketing.getExpiryDate()!=null && byCommericalAndMarketing.getLimitType().equals("NORMAL")){
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            String format = sdf.format(byCommericalAndMarketing.getExpiryDate());
                            expiryDateStr.append(format).append("/");
                        }
                    }
                    if(!StringUtils.isEmpty(deposit.toString())){
                        deposit.deleteCharAt(deposit.length() - 1);
                        depositStr.append(deposit).append("/");
                    }
                    if(!StringUtils.isEmpty(deposit2.toString())){
                        deposit2.deleteCharAt(deposit2.length() - 1);
                        depositStr1.append(deposit2).append("/");

                    }
                }

            }
            if(!StringUtils.isEmpty(depositStr.toString())){
                depositStr.deleteCharAt(depositStr.length() - 1);
                approvalStatusReport.setOriginalSecurityRatio(depositStr.toString());
            }
            /*if(!StringUtils.isEmpty(depositStr1.toString())){
                depositStr1.deleteCharAt(depositStr1.length() - 1);
                approvalStatusReport.setUpdatedSecurityRatio(depositStr1.toString());
            }*/
            if(!StringUtils.isEmpty(sectorStr.toString())){
                sectorStr.deleteCharAt(sectorStr.length() - 1);
                approvalStatusReport.setSector(sectorStr.toString());
            }
            if(!StringUtils.isEmpty(dealerCodeStr.toString())){
                dealerCodeStr.deleteCharAt(dealerCodeStr.length() - 1);
                approvalStatusReport.setDealerCode(dealerCodeStr.toString());
            }
            if(!StringUtils.isEmpty(expiryDateStr.toString())){
                expiryDateStr.deleteCharAt(expiryDateStr.length() - 1);
                approvalStatusReport.setExpiryDate(expiryDateStr.toString());
            }
            reports.add(approvalStatusReport);
        }
        if(reports.size()==0 && (instanceId.contains("ALD") || instanceId.contains("ALT"))){
            //需要从别的表单取
            ActiveLimitAdjustmentProposal adjustmentProposalTemp = new ActiveLimitAdjustmentProposal();
            adjustmentProposalTemp.setInstanceId(instanceId);
            List<ActiveLimitAdjustmentProposal> activeLimitAdjustmentProposals = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalList1(adjustmentProposalTemp);
            for (ActiveLimitAdjustmentProposal limitAdjustmentProposal : activeLimitAdjustmentProposals) {
                //一个经销商一条
                ActiveLimitAdjustmentProposal adjustmentProposal = new ActiveLimitAdjustmentProposal();
                adjustmentProposal.setInstanceId(instanceId);
                ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
                approvalStatusReport.setInstanceId(instanceId);
                approvalStatusReport.setDealerNameCn(limitAdjustmentProposal.getDealerName());
                DealerInformation dealerInformation = new DealerInformation();
                dealerInformation.setDealerName(limitAdjustmentProposal.getDealerName());
                dealerInformation.setMake(limitAdjustmentProposal.getSector());
                List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
                String enName = dealerInformations.get(0).getEnName() == null ? " " : dealerInformations.get(0).getEnName();
                String group = dealerInformations.get(0).getGroupName() == null ? " " : dealerInformations.get(0).getGroupName();
                approvalStatusReport.setDealerNameEn(enName);
                approvalStatusReport.setGroup(group);
                adjustmentProposal.setDealerName(limitAdjustmentProposal.getDealerName());
                //其他信息用/分开
                StringBuilder sectorStr = new StringBuilder();
                StringBuilder dealerCodeStr = new StringBuilder();
                StringBuilder depositStr = new StringBuilder();
                List<ActiveLimitAdjustmentProposal> activeLimitAdjustmentProposals1 = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalList(adjustmentProposal);

                Long currentLimitSum = 0l;
                Long proposedLimitSum = 0l;
                if(activeLimitAdjustmentProposals1!=null && activeLimitAdjustmentProposals1.size()>0){
                    for (ActiveLimitAdjustmentProposal proposal : activeLimitAdjustmentProposals1) {
                        if(proposal.getActiveLimit()!=null){
                            currentLimitSum = currentLimitSum+proposal.getActiveLimit();
                        }
                        if(proposal.getProposedActiveLimit()!=null){
                            String s = proposal.getProposedActiveLimit();
                            String replace = s.replace(",", "");
                            proposedLimitSum =proposedLimitSum+Long.valueOf(replace);
                        }

                    }
                    approvalStatusReport.setOriginalLimit(currentLimitSum.toString());
                    //approvalStatusReport.setUpdatedLimit(proposedLimitSum.toString());
                }
                List<ActiveLimitAdjustmentProposal> activeLimitAdjustmentProposals2 = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalList2(adjustmentProposal);
                for (ActiveLimitAdjustmentProposal proposal : activeLimitAdjustmentProposals2) {
                    sectorStr.append(proposal.getSector()).append("/");
                    dealerCodeStr.append(proposal.getDealerCode()).append("/");
                    adjustmentProposal.setSector(proposal.getSector());
                    List<ActiveLimitAdjustmentProposal> activeLimitAdjustmentProposals3 = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalList3(adjustmentProposal);
                    if(activeLimitAdjustmentProposals3!=null && activeLimitAdjustmentProposals3.size()>0){
                        StringBuilder deposit = new StringBuilder();
                        for (ActiveLimitAdjustmentProposal activeLimitAdjustmentProposal1 : activeLimitAdjustmentProposals3) {
                            if(!StringUtils.isEmpty(activeLimitAdjustmentProposal1.getCurrentCashDeposit())){
                                deposit.append(activeLimitAdjustmentProposal1.getCurrentCashDeposit()).append(",");
                            }
                        }
                        if(!StringUtils.isEmpty(deposit.toString())){
                            deposit.deleteCharAt(deposit.length() - 1);
                            depositStr.append(deposit).append("/");
                        }
                    }

                }
                if(!StringUtils.isEmpty(depositStr.toString())){
                    depositStr.deleteCharAt(depositStr.length() - 1);
                    approvalStatusReport.setOriginalSecurityRatio(depositStr.toString());
                }
                if(!StringUtils.isEmpty(sectorStr.toString())){
                    sectorStr.deleteCharAt(sectorStr.length() - 1);
                    approvalStatusReport.setSector(sectorStr.toString());
                }
                if(!StringUtils.isEmpty(dealerCodeStr.toString())){
                    dealerCodeStr.deleteCharAt(dealerCodeStr.length() - 1);
                    approvalStatusReport.setDealerCode(dealerCodeStr.toString());
                }
                reports.add(approvalStatusReport);
            }

        }
        //如果还是没有就拿经销商
        if(reports.size()==0){
            List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
            for (BasicInformation basicInformation : basicInformations) {
                ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
                approvalStatusReport.setInstanceId(instanceId);
                approvalStatusReport.setDealerNameCn(basicInformation.getDealerNameCN());
                approvalStatusReport.setDealerNameEn(basicInformation.getDealerNameEN());
                approvalStatusReport.setGroup(basicInformation.getGroupNameEN());
                StringBuilder sectorStr = new StringBuilder();
                StringBuilder dealerCodeStr = new StringBuilder();
                String dealerCodeFromWFS = basicInformation.getDealerCodeFromWFS();
                String sector = basicInformation.getSector();
                if(!StringUtils.isEmpty(dealerCodeFromWFS)){
                    String replace = dealerCodeFromWFS.replace("[", "").replace("]", "");
                    String[] split = replace.split(",");
                    for (String s : split) {
                        dealerCodeStr.append(s).append("/");
                    }
                }
                if(!StringUtils.isEmpty(sector)){
                    String[] split = sector.split(",");
                    for (String s : split) {
                        sectorStr.append(s).append("/");
                    }
                }
                if(!StringUtils.isEmpty(sectorStr.toString())){
                    sectorStr.deleteCharAt(sectorStr.length() - 1);
                    approvalStatusReport.setSector(sectorStr.toString());
                }
                if(!StringUtils.isEmpty(dealerCodeStr.toString())){
                    dealerCodeStr.deleteCharAt(dealerCodeStr.length() - 1);
                    approvalStatusReport.setDealerCode(dealerCodeStr.toString());
                }
                reports.add(approvalStatusReport);
            }
        }

        for (ApprovalStatusReport report : reports) {
            report.setRequirement(annualReviewy.getTitle());
            //此时查询UW
/*            if(StringUtils.isNotEmpty(report.getDealerNameCn())){
                HDealerDm hDealerDm = hDealerDmMapper.selectHDealerDmByDealerName(report.getDealerNameCn());
                if(hDealerDm!=null && StringUtils.isNotEmpty(hDealerDm.getUwName())){
                    report.setResponsibleUw(hDealerDm.getUwName());
                }
            }*/
            report.setSituation("Under Evaluation");
            approvalStatusReportService.insertApprovalStatusReport(report);
            saveDbLog("1","新增流程",null,instanceId,null,report,null);
        }
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        saveDbLog("1","新增流程",null ,instanceId,null,annualReviewy,null);


        //非草稿行为，提交流程 发送邮件
        if(map.get("caoGao") == null || !map.get("caoGao").toString().equals("1")){
            //发送邮件
            try {
                org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                        .processInstanceId(task.getProcessInstanceId())
                        .singleResult();
                // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                        .processInstanceId(processInstanceMe.getProcessInstanceId())
                        .singleResult();

                ThreadUtil.execute(new Runnable() {

                    @Override
                    public void run() {
                        actTaskService.sendMail(task1, instanceId,null);
                    }
                });

            } catch (Exception e) {
                log.error("邮件发送失败，{}",e.getMessage());
            }
        }

        return i;
    }

    public int updateAnnualReviewyByInstanceId(AnnualReviewy annualReviewy) {
        return annualReviewyMapper.updateAnnualReviewyByInstanceId(annualReviewy);
    }

    public int closeUpdateAnnualReviewyObj(String instanceId, String username) {
        return annualReviewyMapper.closeUpdateAnnualReviewyObj(instanceId, username);
    }

    public int openUpdateAnnualReviewyObj(String username) {
        return annualReviewyMapper.openUpdateAnnualReviewyObj(username);
    }

    @Override
    public List getInfoListByDealerName(String dealerName) {
        List list = dealerInformationMapper.getInfoListByDealerName(dealerName);
        return list;
    }

    /**
     * 修改feike
     *
     * @param map feike
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAnnualReviewy(Map<String, Object> map) {
        String instanceId = (String) map.get("instanceId");
        //更新子流程日期
        if(!StringUtils.isEmpty(instanceId) && instanceId.contains("-") && map.get("taskname")!=null && ("合同生成校验".equals(map.get("taskname")))){
            //更新
            AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
            if(annualReviewy!=null){
                String[] split = instanceId.split("-");
                ContractRecord contractRecord = new ContractRecord();
                contractRecord.setInstanceid(split[0]);
                contractRecord.setDealername(annualReviewy.getDealerName());
                contractRecord.setLimitType(annualReviewy.getLimitType());
                contractRecord.setSector(annualReviewy.getSector() );
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(contractRecord);
                if(contractRecords!=null){
                    for (ContractRecord record : contractRecords) {
                        record.setIssuedate(new Date());
                        contractRecordMapper.updateContractRecord(record);
                    }
                }

            }
        }
        if(map.get("taskname")!=null && ("自发合同审核".equals(map.get("taskname")) || "自发合同-合同修改".equals(map.get("taskname")))){
            //转pdf
            ContractApproval contractApproval = contractApprovalMapper.getInfoByInstanceId(instanceId);
            String fileUrl = contractApproval.getFileUrl();
            if(fileUrl.contains("upload")){
                //说明重新生成了文件，需要截取
                fileUrl = fileUrl.substring(8, fileUrl.length());
            }
            String docPath = RuoYiConfig.getProfile()+fileUrl;
            File file2 = new File(RuoYiConfig.getProfile()+"/contractApproval/pdf/"+instanceId);
            if (file2.mkdirs()) {
                System.out.println("单文件夹"+instanceId+"创建成功！创建后的文件目录为：" + file2.getPath() + ",上级文件为:" + file2.getParent());
            }
            String uuid1 = IdUtils.get16UUID();
            String pdfPath = RuoYiConfig.getProfile()+"/contractApproval/pdf/"+instanceId+"/"+contractApproval.getDealerName()+uuid1+".pdf";
            String pdfPath1 = "/profile/contractApproval/pdf/"+instanceId+"/"+contractApproval.getDealerName()+uuid1+".pdf";
            AsposeUtil.doc2pdf(docPath,pdfPath);
            //查询是否有归档合同 有则更新 无则创建
            DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
            dealercodeContractFiling.setContractLocation(pdfPath1);
            dealercodeContractFiling.setDealerNameCN(contractApproval.getDealerName());
            dealercodeContractFiling.setSector(contractApproval.getSector());
            dealercodeContractFiling.setContractName(contractApproval.getDealerName()+contractApproval.getSector()+"Demo");
            dealercodeContractFiling.setSubProcessId(instanceId);
            dealercodeContractFiling.setInstanceId(instanceId);
            dealercodeContractFiling.setContractLocationHistory(pdfPath1);
            dealercodeContractFiling.setLimitType("Demo");
            DealercodeContractFiling dealercodeContractFiling2 = new DealercodeContractFiling();
            dealercodeContractFiling2.setSubProcessId(instanceId);
            dealercodeContractFiling2.setInstanceId(instanceId);
            dealercodeContractFiling2.setDealerNameCN(contractApproval.getDealerName());
            dealercodeContractFiling2.setSector(contractApproval.getSector());
            List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling2);
            if(StringUtils.isEmpty(dealercodeContractFilings)){
                dealercodeContractFilingMapper.insertDealercodeContractFiling(dealercodeContractFiling);
                saveDbLog("1","自发合同新增合同信息",null,instanceId,null,dealercodeContractFiling,null);
            }else{
                for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                    DealercodeContractFiling dealercodeContractFiling1 = new DealercodeContractFiling();
                    com.ruoyi.common.utils.bean.BeanUtils.copyProperties(contractFiling,dealercodeContractFiling1);
                    contractFiling.setContractLocation(pdfPath1);
                    dealercodeContractFilingMapper.updateDealercodeContractFiling(contractFiling);
                    saveDbLog("3","自发合同修改合同信息",null,instanceId,dealercodeContractFiling1,contractFiling,null);
                }
            }
        }


        String uuid = IdUtils.get16UUID();

        //判断是否出合同 出合同后不修改表单
        DealercodeContract  dealercodeContract =new DealercodeContract();
        dealercodeContract.setInstanceId(instanceId);
        List<DealercodeContract> dealercodeContracts = dealercodeContractService.selectDealercodeContractList(dealercodeContract);
        if(dealercodeContracts!=null && dealercodeContracts.size()>0){
            //说明出合同了
            return 1;
        }

        //判断该流程是否加锁
        try{
            ActWorkflowLock actWorkflowLock = new ActWorkflowLock();
            actWorkflowLock.setId(uuid);
            actWorkflowLock.setTaskid(instanceId);
            actWorkflowLock.setCreateTime(DateUtils.getNowDate());
            iActWorkflowLockService.insertActWorkflowLock(actWorkflowLock);
        }catch (Exception e) {
            e.printStackTrace();
            Throwable cause = e.getCause();
            if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                //错误信息
                String errMsg = ((java.sql.SQLIntegrityConstraintViolationException) cause).getMessage();
                //根据约束名称定位是那个字段
                if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("ux_task_id") != -1) {
                    throw  new BaseException("该流程已锁定,请稍后");
                } else {
                    throw  new BaseException("该流程已锁定,请稍后");
                }
            } else {
                throw  new BaseException("该流程已锁定,请稍后");
            }
        }
        Task task = null;
        try {
            if (map.get("caoGao") != null && map.get("caoGao").toString().equals("0")) { //草稿接口非保存，提交流程
                Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                        .getUser()
                        .getUserId()
                        .toString());
                String title = "";
                if (StringUtils.isNotNull(map.get("name"))) {
                    title = String.valueOf(map.get("name"));
                } else {
                    title = "Annual Review";
                }
                //流程开始
                ProcessInstance processInstance = null;
                if (StringUtils.isNotNull(map.get("processDefinitionKey"))) {
                    processInstance = processRuntime.start(ProcessPayloadBuilder
                            .start()
                            .withProcessDefinitionKey(map.get("processDefinitionKey") + "")
                            .withName(title)
                            .withBusinessKey(instanceId)
                            // .withVariable("deptLeader",join)
                            .build());
                } else {
                    processInstance = processRuntime.start(ProcessPayloadBuilder
                            .start()
                            .withProcessDefinitionKey("annualVerification")
                            .withName(title)
                            .withBusinessKey(instanceId)
                            // .withVariable("deptLeader",join)
                            .build());
                }


                task = taskService.createTaskQuery()
                        .processInstanceId(processInstance.getId())
                        .singleResult();
                TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(SecurityUtils.getUsername()).active();
                List<Task> todoList = query.list();//获取申请人的待办任务列表
                for (Task tmp : todoList) {
                    if (tmp.getProcessInstanceId().equals(processInstance.getId())) {
                        task = tmp;//获取当前流程实例，当前申请人的待办任务
                        break;
                    }
                }
                HashMap<String, Object> variables = new HashMap<String, Object>();
                List<Map<String, Object>> actForm = (List<Map<String, Object>>) map.get("actForm");
                for (Map<String, Object> form : actForm) {
                    variables.put(String.valueOf(form.get("controlId")), form.get("controlValue"));
                }
                variables.put("toUnderwriter", 0);


                taskService.complete(task.getId(), variables);

            }
            // Map<String, Object> basic_informations = (Map<String, Object>) map.get("groupName");
            // if (basic_informations != null) {
            //     BasicInformation basicInformation = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
            //     basicInformation.setGroupNameCN((String) basic_informations.get("groupNameCN"));
            //     basicInformation.setGroupNameEN((String) basic_informations.get("groupNameEN"));
            //     basicInformationMapper.updateBasicInformation(basicInformation);
            // }
            //h_basic_information ============================================
            List<Map<String, Object>> dealernameList = (List<Map<String, Object>>) map.get("dealername");
            Map<String, Object> groupName = (Map<String, Object>) map.get("groupName");
            if (dealernameList != null && dealernameList.size() > 0) {
                for (Map<String, Object> stringObjectMap : dealernameList) {
                    String gm = (String) stringObjectMap.get("GM");
                    String dealerCodeFromManufacturer = (String) stringObjectMap.get("dealerCodeFromManufacturer");
                    String dealerCodeFromWFS = (String) stringObjectMap.get("dealerCodeFromWFS");
                    String dealerNameCN = (String) stringObjectMap.get("dealerNameCN");
                    String dealerNameEN = (String) stringObjectMap.get("dealerNameEN");
                    String dealername = (String) stringObjectMap.get("dealername");
                    String incorporationDate = (String) stringObjectMap.get("incorporationDate");
                    String joinSectorDealerNetworkDate = (String) stringObjectMap.get("joinSectorDealerNetworkDate");
                    String paidupCapital = (String) stringObjectMap.get("paidupCapital");
                    String province = (String) stringObjectMap.get("province");
                    Object relatedWorkingExperience = stringObjectMap.get("relatedWorkingExperience");
                    Integer relatedWorkingExperienceInt = (Integer) relatedWorkingExperience;
                    String value = (String) stringObjectMap.get("value");
                    StringBuilder sector = new StringBuilder();
                    List sectorList = (List) stringObjectMap.get("sector");//数组
                    if (sectorList != null && sectorList.size() > 0) {
                        for (int i = 0; i < sectorList.size(); i++) {
                            sector.append(sectorList.get(i));
                            sector.append(",");
                        }
                    }
                    if (!StringUtils.isEmpty(sector)) {
                        sector.deleteCharAt(sector.length() - 1);
                        System.out.println("sector" + sector);
                    }
                    StringBuilder shareholders = new StringBuilder();

                    Object shareholdersAndShare = stringObjectMap.get("shareholdersAndShare");
                    if (shareholdersAndShare != null) {
                        List shareholdersAndShareList = (List) shareholdersAndShare;//数组
                        if (shareholdersAndShareList != null && shareholdersAndShareList.size() > 0) {
                            for (int i = 0; i < shareholdersAndShareList.size(); i++) {
                                StringBuilder shareholder = new StringBuilder();
                                Map<String, Object> stringObjectMap1 = (Map<String, Object>) shareholdersAndShareList.get(i);
                                String s1 = (String) stringObjectMap1.get("shareholdersCn");
                                String s2 = (String) stringObjectMap1.get("shareholdersEn");
                                String s3 = (String) stringObjectMap1.get("share");
                                shareholder.append(s1);
                                shareholder.append("$|");
                                shareholder.append(s2);
                                shareholder.append("$|");
                                shareholder.append(s3);
                                shareholders.append(shareholder);
                                shareholders.append("#");
                            }
                        }
                    }
                    if (!StringUtils.isEmpty(shareholders)) {
                        shareholders.deleteCharAt(shareholders.length() - 1);
                        System.out.println("shareholders" + shareholders);
                    }
         /*       if (!StringUtils.isEmpty(share)) {
                    share.deleteCharAt(share.length() - 1);
                    System.out.println("share" + share);
                }*/

                    BasicInformation basicInformation = new BasicInformation();
                    if (groupName != null) {
                        basicInformation.setGroupNameCN((String) groupName.get("groupNameCN"));
                        basicInformation.setGroupNameEN((String) groupName.get("groupNameEN"));
                    }
                    basicInformation.setId(IdUtils.simpleUUID());
                    if (!StringUtils.isEmpty(gm)) {
                        basicInformation.setGm(gm);
                    }
                    if (!StringUtils.isEmpty(dealerCodeFromManufacturer) && !("[]".equals(dealerCodeFromManufacturer))) {
                        basicInformation.setDealerCodeFromManufacturer(dealerCodeFromManufacturer);
                    }
                    if (!StringUtils.isEmpty(dealerCodeFromWFS)) {
                        basicInformation.setDealerCodeFromWFS(dealerCodeFromWFS);
                    }
                    if (!StringUtils.isEmpty(dealerNameCN)) {
                        basicInformation.setDealerNameCN(dealerNameCN);
                    }
                    if (!StringUtils.isEmpty(dealerNameEN)) {
                        basicInformation.setDealerNameEN(dealerNameEN);
                    }
                    if (!StringUtils.isEmpty(dealername)) {
                        basicInformation.setDealername(dealername);
                    }
                    if (!StringUtils.isEmpty(incorporationDate)) {
                        basicInformation.setIncorporationDate(incorporationDate);
                    }
                    if (!StringUtils.isEmpty(joinSectorDealerNetworkDate)) {
                        basicInformation.setJoinSectorDealerNetworkDate(joinSectorDealerNetworkDate);
                    }
                    if (!StringUtils.isEmpty(paidupCapital)) {
                        basicInformation.setPaidupCapital(paidupCapital);
                    }
                    if (!StringUtils.isEmpty(province)) {
                        basicInformation.setProvince(province);
                    }
                    if (relatedWorkingExperienceInt != null) {
                        basicInformation.setRelatedWorkingExperience(relatedWorkingExperienceInt);
                    }
                    if (!StringUtils.isEmpty(sector)) {
                        basicInformation.setSector(sector.toString());
                    }
                    if (!StringUtils.isEmpty(shareholders)) {
                        basicInformation.setShareholders(shareholders.toString());
                    }
   /*             if (!StringUtils.isEmpty(share)) {
                    basicInformation.setShare(share.toString());
                }*/
                    if (!StringUtils.isEmpty(value)) {
                        basicInformation.setDealerValue(value);
                    }
                    basicInformation.setInstanceId(instanceId);
                    basicInformationMapper.updateBasicInformation(basicInformation);
                }
            }

            Object corporateGuaranteeInfo = map.get("GuaranteeInfoDate");
            if (corporateGuaranteeInfo != null) {
                List<List<HBasicCorporateGuarantee>> corporateGuaranteeList = (List<List<HBasicCorporateGuarantee>>) corporateGuaranteeInfo;
                List<Map<String, Object>> corporateGuaranteeList1 = (List<Map<String, Object>>) corporateGuaranteeInfo;
                if (corporateGuaranteeList1 != null && corporateGuaranteeList1.size() > 0) {
                    for (Map<String, Object> stringObjectMap : corporateGuaranteeList1) {
                        if (stringObjectMap.get("GuaranteeInfo") != null) {
                            List<HBasicCorporateGuarantee> info = (List<HBasicCorporateGuarantee>) stringObjectMap.get("GuaranteeInfo");
                            String s = JSON.toJSONString(info);
                            List<HBasicCorporateGuarantee> guaranteeInfos = JSON.parseArray(s, HBasicCorporateGuarantee.class);
                            if (guaranteeInfos != null && guaranteeInfos.size() > 0) {
                                basicCorporateGuaranteeMapper.deleteHBasicCorporateGuaranteeByInstanceIdAndName(instanceId,stringObjectMap.get("dealername").toString());
                                for (HBasicCorporateGuarantee corporateGuarantee : guaranteeInfos) {
                                    corporateGuarantee.setInstanceid(instanceId);
                                    basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(corporateGuarantee);
                                }
                            }

                        }
                        if (stringObjectMap.get("CorporateInfo") != null) {
                            List<HBasicCorporate> info2 = (List<HBasicCorporate>) stringObjectMap.get("CorporateInfo");
                            String s1 = JSON.toJSONString(info2);
                            List<HBasicCorporate> CorporateInfoList = JSON.parseArray(s1, HBasicCorporate.class);
                            if (CorporateInfoList != null && CorporateInfoList.size() > 0) {
                                basicCorporateMapper.deleteHBasicCorporateByInstanceIdAndName(instanceId,stringObjectMap.get("dealername").toString());
                                for (HBasicCorporate hBasicCorporate : CorporateInfoList) {
                                    hBasicCorporate.setInstanceid(instanceId);
                                    hBasicCorporate.setDealername(stringObjectMap.get("dealername").toString());
                                    basicCorporateMapper.insertHBasicCorporate(hBasicCorporate);
                                }
                            }

                        }
                    }
                }
            }
            //TODO 没有传来
            //h_detail_information ============================================
            Object dealer_background = map.get("dealer_background");
            if (dealer_background != null) {
                List<DetailInformation> detailInformationList = (List<DetailInformation>) dealer_background;
                String s = JSON.toJSONString(detailInformationList);
                detailInformationList = JSON.parseArray(s, DetailInformation.class);
                for (DetailInformation detailInformation : detailInformationList) {
                    // detailInformation.setDealerId(detailInformation.getId());
                    // detailInformation.setId(IdUtils.simpleUUID());
                    // detailInformation.setInstanceId(instanceId);
                    detailInformationMapper.updateDetailInformation(detailInformation);
                }
            }

            //————————————————————————————————————————————————————————————————————————————————————

            //TODO-已完成
            //h_sales_performance_and_target ============================================
            Object sales_performance_and_targets = map.get("sales_performance_and_target");

            if (sales_performance_and_targets != null) {
                List<Map<String, Object>> salesPerformanceAndTargetVOList = (List<Map<String, Object>>) sales_performance_and_targets;
                System.out.println("salesPerformanceAndTargetVOList==" + salesPerformanceAndTargetVOList);

                if (salesPerformanceAndTargetVOList != null && salesPerformanceAndTargetVOList.size() > 0) {
                    for (Map<String, Object> mapone : salesPerformanceAndTargetVOList) {
                        //表格内容
                        List<Map<String, Object>> children = (List<Map<String, Object>>) mapone.get("children");
                        //表格头
                        Map<String, Object> title1 = (Map<String, Object>) mapone.get("title");
                        //取表格头动态部分
                        List<Map<String, Object>> second = (List<Map<String, Object>>) title1.get("second");
                        StringBuilder stringBuilder = new StringBuilder();
                        for (Map<String, Object> secondhead : second) {
                            String title2 = secondhead.get("title").toString();
                            stringBuilder.append(title2).append(",");
                        }
                        String s = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
                        for (Map<String, Object> maptwo : children) {
                            if(maptwo.get("id")!=null){
                                SalesPerformanceAndTarget salesPerformanceAndTarget = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetById(maptwo.get("id").toString());
                                SalesPerformanceAndTarget outBean = new SalesPerformanceAndTarget();
                                com.ruoyi.common.utils.bean.BeanUtils.copyProperties(salesPerformanceAndTarget,outBean);
                                if (null != salesPerformanceAndTarget) {
                                    salesPerformanceAndTarget.setDealername(maptwo.get("dealerName").toString());
                                    salesPerformanceAndTarget.setItem(maptwo.get("Item").toString());
                                    salesPerformanceAndTarget.setSector(maptwo.get("Sector").toString());
                                    if (!StringUtils.isEmpty(maptwo.get(second.get(0).get("title")).toString())) {
                                        salesPerformanceAndTarget.setActual2021(Long.parseLong(maptwo.get(second.get(0).get("title")).toString()));
                                    }
                                    if (!StringUtils.isEmpty(maptwo.get(second.get(1).get("title")).toString())) {
                                        salesPerformanceAndTarget.setActualYTD2022(Long.parseLong(maptwo.get(second.get(1).get("title")).toString()));
                                    }
                                    if(!StringUtils.isEmpty(maptwo.get("currentYear").toString())){
                                        salesPerformanceAndTarget.setTarget2022(maptwo.get("currentYear").toString());
                                    }
                                    salesPerformanceAndTargetMapper.updateSalesPerformanceAndTarget(salesPerformanceAndTarget);
                                    saveDbLog("3","修改表单信息","OTHER FINANCING RESOURCE",instanceId,outBean,salesPerformanceAndTarget,null);
                                }
                            }

                        }
                    }
                }
            }




            //TODO-已完成，------
            //h_limit_calculation_for_commerical_needs ============================================
            Object limit_calculation_for_commerical_needs1 = map.get("limit_calculation_for_commerical_needs");
            if (limit_calculation_for_commerical_needs1 != null) {
                LimitCalculationForCommericalNeeds dealerInformation = new LimitCalculationForCommericalNeeds();
                dealerInformation.setInstanceId(instanceId);
                List<LimitCalculationForCommericalNeeds> dealerInformations = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsList(dealerInformation);
                for (LimitCalculationForCommericalNeeds information : dealerInformations) {
                    limitCalculationForCommericalNeedsMapper.deleteLimitCalculationForCommericalNeedsById(information.getId());
                    saveDbLog("2","删除表单信息","LIMIT CALCULATION FOR COMMERCIAL NEEDS",instanceId,dealerInformations,null,null);

                }
                Object limitCalculationForCommericalNeedObj = map.get("limit_calculation_for_commerical_needs");
                if (limitCalculationForCommericalNeedObj != null) {
                    List<Map<String, Object>> limitCalculationForCommericalNeeds = (List<Map<String, Object>>) limitCalculationForCommericalNeedObj;
                    System.out.println("limitCalculationForCommericalNeeds==" + limitCalculationForCommericalNeeds);
                    if (limitCalculationForCommericalNeeds != null && limitCalculationForCommericalNeeds.size() > 0) {
                        for (Map<String, Object> limitCalculationForCommericalNeedVO : limitCalculationForCommericalNeeds) {
                            List<Map<String, Object>> limit_calculation_for_commerical_needs = (List<Map<String, Object>>) limitCalculationForCommericalNeedVO.get("limit_calculation_for_commerical_needs");

                            String stringObjectMap = (String) limitCalculationForCommericalNeedVO.get("dealerName");
                            for (Map<String, Object> aa : limit_calculation_for_commerical_needs) {
                                LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed = new LimitCalculationForCommericalNeeds();
                                limitCalculationForCommericalNeed.setId(IdUtils.simpleUUID());
                                limitCalculationForCommericalNeed.setDealername(stringObjectMap);
                                limitCalculationForCommericalNeed.setSector(aa.get("sector").toString());
                                limitCalculationForCommericalNeed.setModel(aa.get("model").toString());
                                if (StringUtils.isNotNull(aa.get("avgLoanAmt"))) {
                                    limitCalculationForCommericalNeed.setAip(Long.parseLong(aa.get("avgLoanAmt").toString()));
                                }
                                if (StringUtils.isNotNull(aa.get("actualAvgDso"))) {
                                    limitCalculationForCommericalNeed.setAtd(aa.get("actualAvgDso").toString());
                                }
                                if (StringUtils.isNotNull(aa.get("estimatedannualwholesaleunits"))) {
                                    limitCalculationForCommericalNeed.setEstimatedannualwholesaleunits(aa.get("estimatedannualwholesaleunits").toString());
                                }
                                if (StringUtils.isNotNull(aa.get("creditlimitfornewvehicle"))) {
                                    limitCalculationForCommericalNeed.setCreditlimitfornewvehicle(aa.get("creditlimitfornewvehicle").toString());
                                }
                                limitCalculationForCommericalNeed.setInstanceId(instanceId);
                                limitCalculationForCommericalNeedsMapper.insertLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
                                saveDbLog("1","新增表单信息","LIMIT CALCULATION FOR COMMERCIAL NEEDS",instanceId,null,limitCalculationForCommericalNeed,null);
                            }

                        }
                    }
                }

            }
            //TODO-已完成，------
            //h_other_financing_resource ============================================
            Object other_financing_resource = map.get("other_financing_resource");
            if (other_financing_resource != null) {
                List<OtherFinancingResourceVO> otherFinancingResourceVOs = new ArrayList<>();
                otherFinancingResourceVOs = (List<OtherFinancingResourceVO>) other_financing_resource;
                String s = JSON.toJSONString(otherFinancingResourceVOs);
                otherFinancingResourceVOs = JSON.parseArray(s, OtherFinancingResourceVO.class);
                for (OtherFinancingResourceVO otherFinancingResourceVO : otherFinancingResourceVOs) {
                    if(otherFinancingResourceVO.getId() == null || otherFinancingResourceVO.getId() ==""){
                        OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                        otherFinancingResource.setId(IdUtils.simpleUUID());
                        otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                        otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                        otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionName());
                        otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoanType());
                        otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedLimit());
                        otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                        otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                        otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestRate());
                        otherFinancingResource.setDueDate(otherFinancingResourceVO.getDueDate());
                        otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                        //otherFinancingResource.setInstanceId(instanceId);
                        otherFinancingResourceMapper.insertOtherFinancingResource(otherFinancingResource);
                        saveDbLog("1","新增表单信息","OTHER FINANCING RESOURCE",instanceId,null,otherFinancingResource,null);

                    }else{
                        OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                        OtherFinancingResource otherFinancingResource1 = otherFinancingResourceMapper.selectOtherFinancingResourceById(otherFinancingResourceVO.getId());
                        otherFinancingResource.setId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealerId(otherFinancingResourceVO.getId());
                        otherFinancingResource.setDealername(otherFinancingResourceVO.getDealername());
                        otherFinancingResource.setIndex(otherFinancingResourceVO.getIndex());
                        otherFinancingResource.setInstitutionName(otherFinancingResourceVO.getInstitutionName());
                        otherFinancingResource.setLoanType(otherFinancingResourceVO.getLoanType());
                        otherFinancingResource.setApprovedLimit(otherFinancingResourceVO.getApprovedLimit());
                        otherFinancingResource.setOs(otherFinancingResourceVO.getOs());
                        otherFinancingResource.setSecurity(otherFinancingResourceVO.getSecurity());
                        otherFinancingResource.setInterestRate(otherFinancingResourceVO.getInterestRate());
                        otherFinancingResource.setDueDate(otherFinancingResourceVO.getDueDate());
                        otherFinancingResource.setPurpose(otherFinancingResourceVO.getPurpose());
                        //otherFinancingResource.setInstanceId(instanceId);
                        otherFinancingResourceMapper.updateOtherFinancingResourceByid(otherFinancingResource);
                        saveDbLog("3","修改表单信息","OTHER FINANCING RESOURCE",instanceId,otherFinancingResource1,otherFinancingResource,null);
                    }
                }
            }

            //TODO 没有传来
            //temporary_condition_follow_up ============================================
            Object temporary_condition_follow_up = map.get("temporary_condition_follow_up");
            if (temporary_condition_follow_up != null) {
                List<TemporaryConditionFollowUpVo> temporaryConditionFollowUpVos = new ArrayList<>();
                temporaryConditionFollowUpVos = (List<TemporaryConditionFollowUpVo>) temporary_condition_follow_up;
                String s = JSON.toJSONString(temporaryConditionFollowUpVos);
                temporaryConditionFollowUpVos = JSON.parseArray(s, TemporaryConditionFollowUpVo.class);
                for (TemporaryConditionFollowUpVo temporaryConditionFollowUpVo : temporaryConditionFollowUpVos) {
                    if (null != temporaryConditionFollowUpVo.getId()) {
                        TemporaryConditionFollowUp temporaryConditionFollowUp = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpById(temporaryConditionFollowUpVo.getId());
                        temporaryConditionFollowUp.setDealername(temporaryConditionFollowUpVo.getDealername());
                        temporaryConditionFollowUp.setConditionDate(temporaryConditionFollowUpVo.getConditionDate());
                        temporaryConditionFollowUp.setCondition(temporaryConditionFollowUpVo.getCondition());
                        temporaryConditionFollowUp.setDueDate(temporaryConditionFollowUpVo.getDueDate());
                        String tmp = "";
                        if(null != temporaryConditionFollowUpVo.getRole()){
                            for (int i = 0; i < temporaryConditionFollowUpVo.getRole().size(); i++) {
                                if (i < temporaryConditionFollowUpVo.getRole().size() - 1) {
                                    tmp += temporaryConditionFollowUpVo.getRole().get(i) + ",";
                                } else {
                                    tmp += temporaryConditionFollowUpVo.getRole().get(i);
                                }
                            }
                        }
                        temporaryConditionFollowUp.setRole(tmp);
                        temporaryConditionFollowUp.setComments(temporaryConditionFollowUpVo.getComments());
                        temporaryConditionFollowUp.setCurrentStatus(temporaryConditionFollowUpVo.getCurrentStatus());
                        TemporaryConditionFollowUp temporaryConditionFollowUp1 = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpById(temporaryConditionFollowUpVo.getId());
                        temporaryConditionFollowUpMapper.updateTemporaryConditionFollowUp(temporaryConditionFollowUp);
                        saveDbLog("3","修改表单信息","TEMPORARY CONDITION FOLLOW UP",instanceId,temporaryConditionFollowUp1,temporaryConditionFollowUp,null);
                    } else {
                        TemporaryConditionFollowUp temporaryConditionFollowUp = new TemporaryConditionFollowUp();
                        temporaryConditionFollowUp.setId(IdUtils.simpleUUID());
                        temporaryConditionFollowUp.setDealername(temporaryConditionFollowUpVo.getDealername());
                        temporaryConditionFollowUp.setConditionDate(temporaryConditionFollowUpVo.getConditionDate());
                        temporaryConditionFollowUp.setCondition(temporaryConditionFollowUpVo.getCondition());
                        temporaryConditionFollowUp.setDueDate(temporaryConditionFollowUpVo.getDueDate());
                        String tmp = "";
                        if(null != temporaryConditionFollowUpVo.getRole()) {
                            for (int i = 0; i < temporaryConditionFollowUpVo.getRole().size(); i++) {
                                if (i < temporaryConditionFollowUpVo.getRole().size() - 1) {
                                    tmp += temporaryConditionFollowUpVo.getRole().get(i) + ",";
                                } else {
                                    tmp += temporaryConditionFollowUpVo.getRole().get(i);
                                }
                            }
                        }
                        temporaryConditionFollowUp.setRole(tmp);
                        temporaryConditionFollowUp.setComments(temporaryConditionFollowUpVo.getComments());
                        temporaryConditionFollowUp.setCurrentStatus(temporaryConditionFollowUpVo.getCurrentStatus());
                        temporaryConditionFollowUp.setIsExist(temporaryConditionFollowUpVo.getIsExist());
                        //temporaryConditionFollowUp.setInstanceId(instanceId);
                        temporaryConditionFollowUpMapper.insertTemporaryConditionFollowUp(temporaryConditionFollowUp);
                        saveDbLog("1","新增表单信息","TEMPORARY CONDITION FOLLOW UP",instanceId,null,temporaryConditionFollowUp,null);
                    }
                }
            }

            // 从第三方接口取数据已完成
            //h_proposal_by_commerical_and_marketing ============================================
            // Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing_evaluate");
            Object proposal_by_commerical_and_marketing = map.get("proposal_by_commerical_and_marketing");
            if (proposal_by_commerical_and_marketing != null) {
                List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketings = (List<ProposalByCommericalAndMarketingVO>) proposal_by_commerical_and_marketing;
                String s = JSON.toJSONString(proposalByCommericalAndMarketings);
                ArrayList<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS = new ArrayList<>();
                proposalByCommericalAndMarketings = JSON.parseArray(s, ProposalByCommericalAndMarketingVO.class);
                for (ProposalByCommericalAndMarketingVO proposalByCommericalAndMarketingVO : proposalByCommericalAndMarketings) {
                    ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = new ProposalByCommericalAndMarketing();
                    BeanUtils.copyProperties(proposalByCommericalAndMarketingVO, proposalByCommericalAndMarketing);

                    ThirdCreditInfoSimpleVO thirdCreditInfoSimpleVO = new ThirdCreditInfoSimpleVO();
                    ArrayList<ThirdCreditInfoSimpleChild> childArrayList = new ArrayList<>();
                    thirdCreditInfoSimpleVO.setDealerId(proposalByCommericalAndMarketingVO.getDealerCode());
                    thirdCreditInfoSimpleVO.setDealerName(proposalByCommericalAndMarketingVO.getDealername());
                    ThirdCreditInfoSimpleChild thirdCreditInfoSimpleChild = new ThirdCreditInfoSimpleChild();
                    thirdCreditInfoSimpleChild.setDealerId(proposalByCommericalAndMarketingVO.getDealerCode());
                    thirdCreditInfoSimpleChild.setDealerName(proposalByCommericalAndMarketingVO.getDealername());
                    thirdCreditInfoSimpleChild.setSector(proposalByCommericalAndMarketingVO.getSector());
                    thirdCreditInfoSimpleChild.setLimitType(proposalByCommericalAndMarketingVO.getLimitType());
                    thirdCreditInfoSimpleChild.setExpiryDate(proposalByCommericalAndMarketingVO.getExpiryDate());
                    childArrayList.add(thirdCreditInfoSimpleChild);
                    thirdCreditInfoSimpleVO.setChild(childArrayList);
                    thirdCreditInfoSimpleVOS.add(thirdCreditInfoSimpleVO);
                    if(StringUtils.isNotEmpty(proposalByCommericalAndMarketing.getId())){
                        ProposalByCommericalAndMarketing proposalByCommericalAndMarketing1 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingById(proposalByCommericalAndMarketing.getId());
                        proposalByCommericalAndMarketingMapper.updateProposalByCommericalAndMarketing(proposalByCommericalAndMarketing);
                        saveDbLog("3","修改表单信息","PROPOSAL BY COMMERCIAL & MARKETING",instanceId,proposalByCommericalAndMarketing1,proposalByCommericalAndMarketing,null);


                    }else {
                        proposalByCommericalAndMarketing.setId(IdUtils.simpleUUID());
                        proposalByCommericalAndMarketing.setInstanceId(instanceId);
                        proposalByCommericalAndMarketingMapper.insertProposalByCommericalAndMarketing(proposalByCommericalAndMarketing);
                        saveDbLog("1","新增表单信息","PROPOSAL BY COMMERCIAL & MARKETING",instanceId,null,proposalByCommericalAndMarketing,null);

                    }


                }
                creditConditionService.saveAuditCreditCondition(instanceId, thirdCreditInfoSimpleVOS,"修改表单信息");
            }
            if( (map.get("taskname") != null) && (map.get("taskname").equals("Underwriter") ||
                    map.get("taskname").equals("UnderwriterSelect") || map.get("taskname").equals("Supervisor")
                    || map.get("taskname").equals("Credit Manger") || map.get("taskname").equals("Credit Manager") || map.get("taskname").equals("CRO/RC")
                    || map.get("taskname").equals("OP")) ){
                if (map.get("credit_condition") != null) {//保存修改的credit condition内容,等前端更新好了接口再测,先关着
                    List<ThirdCreditInfoSimpleVO> creditList = JSON.parseArray(JSON.toJSONString(map.get("credit_condition")), ThirdCreditInfoSimpleVO.class);
                    creditConditionService.saveAuditCreditCondition(instanceId, creditList,"修改表单信息");
                }
            }

            //从第三方接口取数据已完成
            //h_wholesale_performance_currently ============================================
            Object wholesale_performance_currently = map.get("wholesale_performance_currently");
            if (wholesale_performance_currently != null) {
                List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlyList = (List<WholesalePerformanceCurrently>) wholesale_performance_currently;
                System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
                String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
                wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceCurrently.class);
                if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                    for (WholesalePerformanceCurrently wholesalePerformanceCurrently : wholesalePerformanceCurrentlyList) {
                        if(wholesalePerformanceCurrently.getId()!=null){
                            WholesalePerformanceCurrently wholesalePerformanceCurrently1 = wholesalePerformanceCurrentlyMapper.selectWholesalePerformanceCurrentlyById(wholesalePerformanceCurrently.getId());
                            wholesalePerformanceCurrentlyMapper.updateWholesalePerformanceCurrently(wholesalePerformanceCurrently);
                            saveDbLog("3","修改表单信息","WHOLESALE PERFORMANCE-CURRENTLY",instanceId,wholesalePerformanceCurrently1,wholesalePerformanceCurrently,null);

                        }
                    }
                }
            }


            //balance_information
            Object balanceInformations = map.get("balance_information");
            if(ObjectUtil.isNotNull(balanceInformations)){
                List<BalanceInformation> balanceInformationList = (List<BalanceInformation>)balanceInformations;
                log.info("balance_information=={}",balanceInformationList);
                String string = JSON.toJSONString(balanceInformationList);
                List<BalanceInformation> blceInfo = JSON.parseArray(string, BalanceInformation.class);
                if(CollectionUtil.isNotEmpty(blceInfo) && blceInfo.size() > 0){
                    for (BalanceInformation balanceInformation : blceInfo) {
                        if(balanceInformation.getId()!=null){
                            BalanceInformation balanceInformation1 = balanceInformationMapper.selectBalanceInformationById(balanceInformation.getId());
                            balanceInformationMapper.updateBalanceInformation(balanceInformation);
                            saveDbLog("3","修改表单信息","Balance Information",instanceId,balanceInformation1,balanceInformation,null);
                        }


                    }
                }
            }


            //从第三方接口取数据已完成,TODO 待确定数据存那张表中
            //h_wholesale_performance_currently ============================================
/*            Object wholesalePerformanceRecentThreeMonthsDso = map.get("wholesale_performance_recent_three_months_dso");
            if (wholesalePerformanceRecentThreeMonthsOs != null) {
                List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlyList = (List<WholesalePerformanceCurrently>) wholesalePerformanceRecentThreeMonthsDso;
                System.out.println("wholesalePerformanceCurrentlyList==" + wholesalePerformanceCurrentlyList);
                String wholesalePerformanceCurrentlyStr = JSON.toJSONString(wholesalePerformanceCurrentlyList);
                wholesalePerformanceCurrentlyList = JSON.parseArray(wholesalePerformanceCurrentlyStr, WholesalePerformanceCurrently.class);
                if (wholesalePerformanceCurrentlyList != null && wholesalePerformanceCurrentlyList.size() > 0) {
                    for (WholesalePerformanceCurrently wholesalePerformanceCurrently : wholesalePerformanceCurrentlyList) {
                        if(wholesalePerformanceCurrently.getId()!=null){
                            WholesalePerformanceCurrently wholesalePerformanceCurrently1 = wholesalePerformanceCurrentlyMapper.selectWholesalePerformanceCurrentlyById(wholesalePerformanceCurrently.getId());
                            wholesalePerformanceCurrentlyMapper.updateWholesalePerformanceCurrently(wholesalePerformanceCurrently);
                            saveDbLog("3","修改表单信息","WHOLESALE PERFORMANCE-RECENT 3 MONTHS DSO",instanceId,wholesalePerformanceCurrently1,wholesalePerformanceCurrently,null);

                        }
                    }
                }
            }*/

            //TODO 没有传来
            //h_wholesale_performance_recent_three_months ============================================
            String wholesale_performance_recent_three_months = (String) map.get("wholesale_performance_recent_three_months");
            if (!StringUtils.isEmpty(wholesale_performance_recent_three_months)) {
                List<WholesalePerformanceRecentThreeMonths> wholesalePerformanceRecentThreeMonths = JSON.parseArray(wholesale_performance_recent_three_months, WholesalePerformanceRecentThreeMonths.class);
                for (WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonth : wholesalePerformanceRecentThreeMonths) {
                    if(wholesalePerformanceRecentThreeMonth.getId()!=null){
                        WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentThreeMonths1 = wholesalePerformanceRecentThreeMonthsMapper.selectWholesalePerformanceRecentThreeMonthsById(wholesalePerformanceRecentThreeMonth.getId());
                        wholesalePerformanceRecentThreeMonthsMapper.updateWholesalePerformanceRecentThreeMonths(wholesalePerformanceRecentThreeMonth);
                        saveDbLog("3","修改表单信息","WHOLESALE PERFORMANCE-RECENT 3 MONTHS AGING",instanceId,wholesalePerformanceRecentThreeMonths1,wholesalePerformanceRecentThreeMonth,null);

                    }
                }
            }

            //active_limit_adjustment_proposal数据项插入
            Object activeLimitAdjustmentProposal = map.get("active_limit_adjustment_proposal");
            if (activeLimitAdjustmentProposal != null) {
                List<Map<String, String>> proposalLists = (List<Map<String, String>>) activeLimitAdjustmentProposal;
                if (proposalLists != null && proposalLists.size() > 0) {
                    for (Map proposal : proposalLists) {
                        ActiveLimitAdjustmentProposal adjustmentProposal = BeanUtil.fillBeanWithMap(proposal, new ActiveLimitAdjustmentProposal(), false);
                        if(adjustmentProposal.getId()!=null){
                            if(adjustmentProposal.getDeposit() ==null|| (adjustmentProposal.getDeposit()!=null && adjustmentProposal.getDeposit().equals("null"))){
                                adjustmentProposal.setDeposit("");
                            }
                            ActiveLimitAdjustmentProposal activeLimitAdjustmentProposal1 = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalById(adjustmentProposal.getId());
                            activeLimitAdjustmentProposalMapper.updateActiveLimitAdjustmentProposal(adjustmentProposal);
                            saveDbLog("3","修改表单信息","ACTIVE LIMIT ADJUSTMENT PROPOSAL",instanceId,activeLimitAdjustmentProposal1,adjustmentProposal,null);

                        }
                    }
                }
            }

            //修改cbFleetDetails
            //先删
            Object cbFleetDetail = map.get("cb_fleet_details");
            if(map.get("taskname")!=null && ("DM".equals(map.get("taskname")))){
                CbFleetDetails cbFleetDetails = new CbFleetDetails();
                cbFleetDetails.setInstanceId(instanceId);
                List<CbFleetDetails> cbfleetDetailsList = cbFleetDetailsMapper.selectCbFleetDetailsList(cbFleetDetails);
                for (CbFleetDetails fleetDetails : cbfleetDetailsList) {
                    cbFleetDetailsMapper.deleteCbFleetDetailsById(fleetDetails.getId());
                }
                if (cbFleetDetail != null) {
                    List<CbFleetDetails> cbFleetDetailList = JSON.parseArray(JSON.toJSONString(cbFleetDetail), CbFleetDetails.class);
                    if (cbFleetDetailList != null && cbFleetDetailList.size() > 0) {
                        for (CbFleetDetails fleet : cbFleetDetailList) {
                                fleet.setId(IdUtils.simpleUUID());
                                fleet.setInstanceId(instanceId);
                                fleet.setCreateTime(new Date());
                                fleet.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                                cbFleetDetailsMapper.insertCbFleetDetails(fleet);
                                saveDbLog("1","新增表单信息","CB Fleet Details",instanceId,null,fleet,null);
                        }
                    }
                }
            }else{
                if (cbFleetDetail != null) {
                    List<CbFleetDetails> cbFleetDetailList = JSON.parseArray(JSON.toJSONString(cbFleetDetail), CbFleetDetails.class);
                    if (cbFleetDetailList != null && cbFleetDetailList.size() > 0) {
                        for (CbFleetDetails fleet : cbFleetDetailList) {
                            if(StringUtils.isEmpty(fleet.getId())){
                                fleet.setId(IdUtils.simpleUUID());
                                fleet.setInstanceId(instanceId);
                                fleet.setCreateTime(new Date());
                                fleet.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                                cbFleetDetailsMapper.insertCbFleetDetails(fleet);
                                saveDbLog("1","新增表单信息","CB Fleet Details",instanceId,null,fleet,null);
                            }else {
                                CbFleetDetails cbFleetDetails = cbFleetDetailsMapper.selectCbFleetDetailsById(fleet.getId());
                                cbFleetDetailsMapper.updateCbFleetDetails(fleet);
                                saveDbLog("3","修改表单信息","CB Fleet Details",instanceId,cbFleetDetails,fleet,null);

                            }
                        }
                    }
                }
            }
            //h_securities ============================================
            String securitiesList = JSON.toJSONString(map.get("securities"));
            System.out.println("securitiesList==" + securitiesList);
            if (!StringUtils.isEmpty(securitiesList)) {
                List<SecuritieVO> securitiesLists = JSON.parseArray(securitiesList, SecuritieVO.class);
                if (securitiesLists != null && securitiesLists.size() > 0) {
                    for (SecuritieVO securitieVO : securitiesLists) {
                        List<Securities> children = securitieVO.getChildren();
                        if (null != children && children.size() > 0) {
                            for (Securities child : children) {
                                //child.setDealername(securitieVO.getDealername());
                                // child.setId(IdUtils.simpleUUID());
                                //child.setInstanceId(instanceId);
                                if(StringUtils.isEmpty(child.getId())){
                                    child.setId(IdUtils.simpleUUID());
                                    child.setInstanceId(instanceId);
                                    child.setDealername(securitieVO.getDealername());
                                    child.setCreateTime(new Date());
                                    child.setCreateBy(SecurityUtils.getUsername());
                                    if(!StringUtils.isEmpty(child.getProposalNameCN())){
                                        child.setProposalNameCN(child.getProposalNameCN());
                                    }else{
                                        child.setProposalNameCN(null);
                                    }
                                    if(!StringUtils.isEmpty(child.getProposalNameEN())){
                                        child.setProposalNameEN(child.getProposalNameEN());
                                    }else{
                                        child.setProposalNameEN(null);
                                    }
                                    securitiesMapper.insertSecurities(child);
                                    saveDbLog("1","新增表单信息","GUARANTEE INFORMATION",instanceId,null,child,null);

                                }else {
                                    if(!StringUtils.isEmpty(child.getProposalNameCN())){
                                        child.setProposalNameCN(child.getProposalNameCN());
                                    }else{
                                        child.setProposalNameCN(null);
                                    }
                                    if(!StringUtils.isEmpty(child.getProposalNameEN())){
                                        child.setProposalNameEN(child.getProposalNameEN());
                                    }else{
                                        child.setProposalNameEN(null);
                                    }
                                    Securities securities = securitiesMapper.selectSecuritiesById(child.getId());
                                    securitiesMapper.updateSecurities(child);
                                    saveDbLog("3","修改表单信息","GUARANTEE INFORMATION",instanceId,securities,child,null);

                                }
                            }
                        }
                    }
                }
            }
            AnnualReviewy annualReviewyTemp = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
            Boolean isAr = false;
            if(annualReviewyTemp!=null && annualReviewyTemp.getType().equals("annualVerification")){
                isAr =  true ;
            }
            if(!StringUtils.isEmpty(instanceId) && (instanceId.contains("NA" )|| isAr) && map.get("taskname")!=null && ("DM".equals(map.get("taskname")))){
                //根据担保公司新增记录 历史有就删除
                HBasicCorporateGuarantee hBasicCorporateGuarantee = new HBasicCorporateGuarantee();
                hBasicCorporateGuarantee.setInstanceid(instanceId);
                List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeList(hBasicCorporateGuarantee);
                if (hBasicCorporateGuarantees != null && hBasicCorporateGuarantees.size() > 0) {
                    basicCorporateGuaranteeMapper.deleteHBasicCorporateGuaranteeByInstanceId(instanceId);
                }
                //生成新的
                List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceIdGroupName(instanceId);
                if(securities!=null && securities.size()>0){
                    for (Securities security : securities) {
                        List<Securities> securities1 = securitiesMapper.selectSecuritiesByInstanceIdAndName2(instanceId, security.getDealername());
                        if(securities1!=null && securities1.size()>0){
                            for (Securities securities2 : securities1) {
                                if(securities2.getGuaranteeType()!=null && securities2.getGuaranteeType().equals("corporate")){
                                    HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                                    hBasicCorporateGuaranteeNew.setDealername(securities2.getDealername());
                                    hBasicCorporateGuaranteeNew.setProposalNameCN(securities2.getProposalNameCN());
                                    hBasicCorporateGuaranteeNew.setInstanceid(instanceId);
                                    //查询在dealer info 是否存在
                                    List<DealerInformation> dealerInformationsHistory = dealerInformationMapper.selectDealerInformationByDealerName(securities2.getDealername());
                                    if(dealerInformationsHistory!=null && dealerInformationsHistory.size()>0 ){
                                        if(dealerInformationsHistory.get(0).getCorporateGuarantorJson()!=null){
                                            String corporateGuarantorJson = dealerInformationsHistory.get(0).getCorporateGuarantorJson();
                                            if(StringUtils.isNotEmpty(corporateGuarantorJson)){
                                                String[] CorporateGuarantor = corporateGuarantorJson.split(";");
                                                for(String co: CorporateGuarantor){
                                                    Map<String, Object> CorporateGuarantorJsonMap = new HashMap<>();
                                                    String[] CorporateGuarantorStr = co.split("#");
                                                    if(CorporateGuarantorStr!=null){
                                                        int length = CorporateGuarantorStr.length;
                                                        if(length ==4){
                                                            String proposalNameCN = CorporateGuarantorStr[0];
                                                            if(proposalNameCN.equals(securities2.getProposalNameCN())){
                                                                hBasicCorporateGuaranteeNew.setGuarantorindustry(CorporateGuarantorStr[1]);
                                                                hBasicCorporateGuaranteeNew.setGuarantorregioncode(CorporateGuarantorStr[2]);
                                                                hBasicCorporateGuaranteeNew.setGuarantorscale(CorporateGuarantorStr[3]);
                                                            }
                                                        }

                                                    }
                                                }
                                            }
                                        }

                                    }
                                    basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                                }
                            }
                        }else{
                            HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                            hBasicCorporateGuaranteeNew.setDealername(security.getDealername());
                            hBasicCorporateGuaranteeNew.setProposalNameCN("-");
                            hBasicCorporateGuaranteeNew.setInstanceid(instanceId);
                            hBasicCorporateGuaranteeNew.setGuarantorscale("-");
                            hBasicCorporateGuaranteeNew.setGuarantorregioncode("-");
                            hBasicCorporateGuaranteeNew.setGuarantorindustry("-");
                            basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                        }
                    }
                }else{
                    List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByDealerName(instanceId);
                    for (BasicInformation basicInformation : basicInformations) {
                        HBasicCorporateGuarantee hBasicCorporateGuaranteeNew = new HBasicCorporateGuarantee();
                        hBasicCorporateGuaranteeNew.setDealername(basicInformation.getDealerNameCN());
                        hBasicCorporateGuaranteeNew.setProposalNameCN("-");
                        hBasicCorporateGuaranteeNew.setInstanceid(instanceId);
                        hBasicCorporateGuaranteeNew.setGuarantorscale("-");
                        hBasicCorporateGuaranteeNew.setGuarantorregioncode("-");
                        hBasicCorporateGuaranteeNew.setGuarantorindustry("-");
                        basicCorporateGuaranteeMapper.insertHBasicCorporateGuarantee(hBasicCorporateGuaranteeNew);
                    }
                }
                //还需要生成担保公司信息
                HBasicCorporate hBasicCorporate2 = new HBasicCorporate();
                hBasicCorporate2.setInstanceid(instanceId);
                List<HBasicCorporate> hBasicCorporates1 = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate2);
                if(hBasicCorporates1 == null || hBasicCorporates1.size() ==0 ){
                    List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByDealerName(instanceId);
                    for (BasicInformation basicInformation : basicInformations) {
                        HBasicCorporate hBasicCorporate = new HBasicCorporate();
                        hBasicCorporate.setDealername(basicInformation.getDealerNameCN());
                        hBasicCorporate.setInstanceid(instanceId);
                        List<DealerInformation> dealer = dealerInformationMapper.selectDealerInformationByDealerName(basicInformation.getDealerNameCN());
                        if(dealer!=null && dealer.size()>0){
                            if(dealer.get(0).getProvince()!=null){
                                hBasicCorporate.setProvince(dealer.get(0).getProvince());
                            }
                            if(dealer.get(0).getCity()!=null){
                                hBasicCorporate.setCity(dealer.get(0).getCity());
                            }
                            if(dealer.get(0).getPeopleSum()!=null){
                                hBasicCorporate.setPeoplesum(dealer.get(0).getPeopleSum());
                            }
                            if(dealer.get(0).getEnterpriseType()!=null){
                                hBasicCorporate.setEnterprisetype(dealer.get(0).getEnterpriseType());
                            }
                            if(dealer.get(0).getDownLoanAccount()!=null){
                                hBasicCorporate.setDownloanaccount(dealer.get(0).getDownLoanAccount());
                            }
                        }
                        basicCorporateMapper.insertHBasicCorporate(hBasicCorporate);
                    }
                }
            }


       /* if(map.get("securities")!=null){
            List<SecuritieVO> securitiesList = (List<SecuritieVO>)map.get("securities");
            // System.out.println("securitiesList==" + securitiesList);
            // if (!StringUtils.isEmpty(securitiesList)) {
            //     List<SecuritieVO> securitiesLists = JSON.parseArray(securitiesList, SecuritieVO.class);
            //     if (securitiesLists != null && securitiesLists.size() > 0) {
                    for (SecuritieVO securitieVO : securitiesList) {
                        List<Securities> children = securitieVO.getChildren();
                        if(null!=children&&children.size()>0){
                            for (Securities child : children) {
                                Securities securitie = securitiesMapper.selectSecuritiesById(child.getId());
                                BeanUtils.copyProperties(child, securitie);
                                securitiesMapper.updateSecurities(securitie);
                            }
                        }
                    // }
                // }
            }
        }*/

            //h_notes ============================================
            Notes notes = notesMapper.selectNotesByInstanceId(instanceId);
            if (notes != null) {
                Notes notes1 = new Notes();
                com.ruoyi.common.utils.bean.BeanUtils.copyProperties(notes,notes1);
                notes.setBasicNotes((String) map.get("basicNotes"));
                notes.setDealerNotes((String) map.get("dealerNotes"));
                notes.setLoyaltyNotes((String) map.get("loyaltyNotes"));
                notes.setAuditNotes((String) map.get("auditNotes"));
                notes.setWholesaleNotes((String) map.get("wholesaleNotes"));
                notes.setProposalNotes((String) map.get("proposalNotes"));
                notes.setCreditComments((String) map.get("creditComments"));
                notes.setGuaranteeNotes((String) map.get("guaranteeNotes"));
                notes.setAmlNotes((String) map.get("amlNotes"));
                notes.setComments((String) map.get("comments"));
                notes.setConditionNotes((String) map.get("conditionNotes"));
                notesMapper.updateNotes(notes);
                saveDbLog("3","修改表单信息","Notes",instanceId,notes1,notes,null);

            }

            Object application1 = map.get("contractSubprocess");
            if (application1 != null) {
                List<Map> applications = (List<Map>) application1;
                for (Map fileuploadVO : applications) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("contractSubprocess");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("contractSubprocess");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object application = map.get("application");
            if (application != null) {
                List<Map> applications = (List<Map>) application;
                for (Map fileuploadVO : applications) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("application");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("application");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object information = map.get("information");
            if (information != null) {
                List<Map> informations = (List<Map>) information;
                for (Map fileuploadVO : informations) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("information");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("information");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object financials = map.get("financials");
            if (financials != null) {
                List<Map> financialss = (List<Map>) financials;
                for (Map fileuploadVO : financialss) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("financials");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("financials");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object guarantee = map.get("guarantee");
            if (guarantee != null) {
                List<Map> guarantees = (List<Map>) guarantee;
                for (Map fileuploadVO : guarantees) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("guarantee");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("guarantee");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object corporate = map.get("corporate");
            if (corporate != null) {
                List<Map> corporates = (List<Map>) corporate;
                for (Map fileuploadVO : corporates) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("corporate");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("corporate");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object other = map.get("other");
            if (other != null) {
                List<Map> others = (List<Map>) other;
                for (Map fileuploadVO : others) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("other");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("other");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object financialAnalysis = map.get("financialAnalysis");
            if (financialAnalysis != null) {
                List<Map> financialAnalysiss = (List<Map>) financialAnalysis;
                for (Map fileuploadVO : financialAnalysiss) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("financialAnalysis");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("financialAnalysis");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object pboc = map.get("pboc");
            if (pboc != null) {
                List<Map> pbocs = (List<Map>) pboc;
                for (Map fileuploadVO : pbocs) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("pboc");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("pboc");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object lawsuit = map.get("lawsuit");
            if (lawsuit != null) {
                List<Map> lawsuits = (List<Map>) lawsuit;
                for (Map fileuploadVO : lawsuits) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("lawsuit");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("lawsuit");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object opDocument = map.get("opDocument");
            if (opDocument != null) {
                List<Map> opDocuments = (List<Map>) opDocument;
                for (Map fileuploadVO : opDocuments) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("opDocument");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("opDocument");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }
            if(map.get("isAdopt")!=null && "4".equals(map.get("isAdopt").toString()) ){
                //说明DM要上传归档合同
                DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
                dealercodeContractFiling.setSubProcessId(instanceId);
                List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling);
                if(dealercodeContractFilings!=null && dealercodeContractFilings.size()>0){
                    String name = dealercodeContractFilings.get(0).getContractNameHistory();
                    if(StringUtils.isEmpty(name)){
                        name = dealercodeContractFilings.get(0).getContractName();
                    }
                    Fileupload fileuploadTemp = new Fileupload();
                    fileuploadTemp.setInstanceId(instanceId);
                    fileuploadTemp.setType("opDocument");
                    List<Fileupload> fileuploadList = fileuploadService.selectFileuploadList(fileuploadTemp);
                    if(fileuploadList!=null && fileuploadList.size()>0){
                        if(fileuploadList.size()==1){
                            if(fileuploadList.get(0).getFileName()!=null && fileuploadList.get(0).getOriginalFileName().toLowerCase().contains("pdf")){
                                for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                                    contractFiling.setContractLocationHistory(fileuploadList.get(0).getFileName());
                                    dealercodeContractFilingMapper.updateDealercodeContractFiling(contractFiling);
                                    //根据归档表查询报表，更新
                                    ContractRecord record = new ContractRecord();
                                    record.setInstanceid(contractFiling.getInstanceId());
                                    record.setDealername(contractFiling.getDealerNameCN());
                                    record.setSector(contractFiling.getSector());
                                    record.setLimitType(contractFiling.getLimitType());
                                    List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(record);
                                    if(CollectionUtil.isNotEmpty(contractRecords)){
                                        for(ContractRecord cr : contractRecords){
                                            cr.setFileUrl(fileuploadList.get(0).getFileName());
                                            cr.setStatus("盖章");
                                            contractRecordMapper.updateContractRecord(cr);
                                        }
                                    }
                                }
                            }
                        }else{
                            List<File> files = new ArrayList();
                            for (Fileupload fileupload : fileuploadList) {
                                if(fileupload.getFileName()!=null && fileupload.getOriginalFileName().toLowerCase().contains("pdf")){
                                    String fileName = fileupload.getFileName();
                                    String newFileName = fileName.substring(8, fileName.length());
                                    String filePath = RuoYiConfig.getProfile() + newFileName;
                                    File newfile = new File(filePath);
                                    files.add(newfile);
                                }
                            }
                            //循环结束合并
                            if(files.size()>0){
                                String uuid1 = IdUtils.get16UUID();
                                String path ="/profile/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+uuid1+"/"+name+".pdf";
                                String dizhi = RuoYiConfig.getProfile() + "/splicepdf/"+DateUtils.getCurrentYear()+"/"+DateUtils.getCurrentMonth()+"/"+instanceId+"/"+uuid1+"/"+name+".pdf";
                                File newfile = new File(dizhi);
                                File fileParent = newfile.getParentFile();
                                System.out.println(fileParent);
                                //判断是否存在
                                if (!fileParent.exists()) {
                                    // 创建父目录文件夹
                                    fileParent.mkdirs();
                                }
                                File f = AsposeUtil.MulFileToOne(files, dizhi);
                                for (DealercodeContractFiling contractFiling : dealercodeContractFilings) {
                                    contractFiling.setContractLocationHistory(path);
                                    dealercodeContractFilingMapper.updateDealercodeContractFiling(contractFiling);
                                    //根据归档表查询报表，更新
                                    ContractRecord record = new ContractRecord();
                                    record.setInstanceid(contractFiling.getInstanceId());
                                    record.setDealername(contractFiling.getDealerNameCN());
                                    record.setSector(contractFiling.getSector());
                                    record.setLimitType(contractFiling.getLimitType());
                                    List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(record);
                                    if(CollectionUtil.isNotEmpty(contractRecords)){
                                        for(ContractRecord cr : contractRecords){
                                            cr.setFileUrl(path);
                                            cr.setStatus("盖章");
                                            contractRecordMapper.updateContractRecord(cr);
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }

            Object opDocumentFax = map.get("opDocumentFax");
            if (opDocumentFax != null) {
                List<Map> opDocumentFaxs = (List<Map>) opDocumentFax;
                for (Map fileuploadVO : opDocumentFaxs) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("opDocumentFax");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("opDocumentFax");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }

            Object underwriterOther = map.get("underwriterOther");
            if (underwriterOther != null) {
                List<Map> underwriterOthers = (List<Map>) underwriterOther;
                for (Map fileuploadVO : underwriterOthers) {
                    if (null == fileuploadVO.get("id")) {
                        Fileupload fileupload = new Fileupload();
                        fileupload.setFileName(fileuploadVO.get("fileName").toString());
                        fileupload.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileupload.setUrl(fileuploadVO.get("url").toString());
                        fileupload.setId(IdUtils.simpleUUID());
                        fileupload.setInstanceId(instanceId);
                        fileupload.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                        fileupload.setCreateName(SecurityUtils.getNickName());
                        fileupload.setCreateTime(new Date());
                        fileupload.setType("underwriterOther");
                        Fileupload fileuploadTemp = new Fileupload();
                        fileuploadTemp.setInstanceId(instanceId);
                        fileuploadTemp.setType("underwriterOther");
                        fileuploadTemp.setOriginalFileName(fileuploadVO.get("originalFilename").toString());
                        fileuploadTemp.setUrl(fileuploadVO.get("url").toString());
                        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileuploadTemp);
                        if(fileuploads==null || fileuploads.size()==0){
                            fileuploadService.insertFileupload(fileupload);
                            saveDbLog("1","新增表单信息","File Upload",instanceId,null,fileupload,null);

                        }
                    }
                }
            }



            AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);

            AnnualReviewy outBean = new AnnualReviewy();
            if(annualReviewy!=null){
                com.ruoyi.common.utils.bean.BeanUtils.copyProperties(annualReviewy,outBean);
                if(annualReviewy.getState()!=null && annualReviewy.getState().equals("6")){
                    annualReviewy.setState("0");
                    ApprovalStatusReportMapper approvalStatusReportMapper = SpringUtils.getBean(ApprovalStatusReportMapper.class);
                    ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
                    approvalStatusReport.setInstanceId(instanceId);
                    List<ApprovalStatusReport> approvalStatusReports = approvalStatusReportMapper.selectApprovalStatusReportList1(approvalStatusReport);
                    if(approvalStatusReports!=null && approvalStatusReports.size()>0){
                        for (ApprovalStatusReport statusReport : approvalStatusReports) {
                            statusReport.setSituation("Under Evaluation");
                            approvalStatusReportMapper.updateApprovalStatusReport(statusReport);
                        }
                    }
                }
                if((map.get("taskname") != null) && map.get("taskname").equals("Sales Head")){
                    ApprovalStatusReportMapper approvalStatusReportMapper = SpringUtils.getBean(ApprovalStatusReportMapper.class);
                    ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
                    approvalStatusReport.setInstanceId(instanceId);
                    List<ApprovalStatusReport> approvalStatusReports = approvalStatusReportMapper.selectApprovalStatusReportList1(approvalStatusReport);
                    if(approvalStatusReports!=null && approvalStatusReports.size()>0){
                        for (ApprovalStatusReport statusReport : approvalStatusReports) {
                            //此时查询UW
                            if(StringUtils.isNotEmpty(statusReport.getDealerNameCn())){
                                HDealerDm hDealerDm = hDealerDmMapper.selectHDealerDmByDealerName(statusReport.getDealerNameCn());
                                if(hDealerDm!=null && StringUtils.isNotEmpty(hDealerDm.getUwName())){
                                    statusReport.setResponsibleUw(hDealerDm.getUwName());
                                    approvalStatusReportMapper.updateApprovalStatusReport(statusReport);
                                }
                            }
                        }
                    }
                }
            }

            String UpdateBy = annualReviewy.getUpdateBy();
            if (null != UpdateBy) {
                annualReviewy.setUpdateBy(UpdateBy + "|" + SecurityUtils.getUsername());
            } else {
                annualReviewy.setUpdateBy(SecurityUtils.getUsername());
            }
            annualReviewy.setLockname(null);
            //检查是否是从草稿处进行提交 是则 AnnualReviewy状态改回0
            if (map.get("caoGao") != null && map.get("caoGao").toString().equals("0")) {
                annualReviewy.setState("0");
            }
            if(ObjectUtil.isNotEmpty(task)){
                annualReviewy.setStartNode(task.getName());
            }
            openUpdateAnnualReviewyObj(SecurityUtils.getUsername());

            Object approvalName = map.get("approvalName");
            if(ObjectUtil.isNotEmpty(approvalName)){
                annualReviewy.setApprovalName(approvalName.toString());
            }
            annualReviewy.setUpdateTime(DateUtils.getNowDate());
            if(map.get("taskname")!=null){
                if(map.get("taskname").equals("Underwriter") || map.get("taskname").equals("UnderwriterSelect")){
                    annualReviewy.setUwApprovalName(SecurityUtils.getNickName());
                }
            }

            int i = annualReviewyMapper.updateAnnualReviewy(annualReviewy);
            saveDbLog("3","修改表单信息",null,instanceId,outBean,annualReviewy,null);

            if(map.get("caoGao") != null && map.get("caoGao").toString().equals("0")){
                //发送邮件
                try {
                    org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                            .processInstanceId(task.getProcessInstanceId())
                            .singleResult();
                    // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
                    org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                            .processInstanceId(processInstanceMe.getProcessInstanceId())
                            .singleResult();

                    ThreadUtil.execute(new Runnable() {

                        @Override
                        public void run() {
                            actTaskService.sendMail(task1, instanceId,null);
                        }
                    });

                } catch (Exception e) {
                    log.error("邮件发送失败，{}",e.getMessage());
                }
            }
            return i;
        }catch (Exception e){
            e.printStackTrace();
            return 500;
        }finally {
            iActWorkflowLockService.deleteActWorkflowLockById(uuid);
        }
    }

    /**
     * 批量删除feike
     *
     * @param ids 需要删除的feikeID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAnnualReviewyByIds(String[] ids) {
        List<AnnualReviewy> annualReviewyList = annualReviewyMapper.selectAnnualReviewyByIds(ids);

        if (annualReviewyList != null && annualReviewyList.size() > 0) {
            for (AnnualReviewy annualReviewy : annualReviewyList) {
                int basicInformation = basicInformationMapper.deleteBasicInformationByInstanceId(annualReviewy.getInstanceId());
                int detailInformatio = detailInformationMapper.deleteDetailInformationByInstanceId(annualReviewy.getInstanceId());
                int sales = salesPerformanceAndTargetMapper.deleteSalesPerformanceAndTargetByInstanceId(annualReviewy.getInstanceId());
                int limit = limitCalculationForCommericalNeedsMapper.deleteLimitCalculationForCommericalNeedsByInstanceId(annualReviewy.getInstanceId());
                int other = otherFinancingResourceMapper.deleteOtherFinancingResourceByInstanceId(annualReviewy.getInstanceId());
                int temporary = temporaryConditionFollowUpMapper.deleteTemporaryConditionFollowUpByInstanceId(annualReviewy.getInstanceId());
                int proposal = proposalByCommericalAndMarketingMapper.deleteProposalByCommericalAndMarketingByInstanceId(annualReviewy.getInstanceId());
                int wholesale = wholesalePerformanceCurrentlyMapper.deleteWholesalePerformanceCurrentlyByInstanceId(annualReviewy.getInstanceId());
                int wholesale111 = wholesalePerformanceRecentThreeMonthsMapper.deleteWholesalePerformanceRecentThreeMonthsByInstanceId(annualReviewy.getInstanceId());
                int securities = securitiesMapper.deleteSecuritiesByInstanceId(annualReviewy.getInstanceId());
            }
        }
        return annualReviewyMapper.deleteAnnualReviewyByIds(ids);
        // return 1;
    }

    /**
     * 删除feike信息
     *
     * @param id feikeID
     * @return 结果
     */
    @Override
    public int deleteAnnualReviewyById(String id) {
        return annualReviewyMapper.deleteAnnualReviewyById(id);
    }

    /**
     * 查询 列表带任务状态
     *
     * @param annualReviewy
     * @return
     */
    @Override
    public List<AnnualReviewy> selectAnnualReviewyAndTaskNameList(AnnualReviewy annualReviewy) {
        List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyList(annualReviewy);
        List<String> collect = annualReviewies.parallelStream()
                .map(wl -> wl.getInstanceId())
                .collect(Collectors.toList());
        if (collect != null && !collect.isEmpty()) {
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceIdIn(collect)
                    .list();
            annualReviewies.forEach(
                    wl -> {
                        Task task = tasks.parallelStream()
                                .filter(t -> t.getProcessInstanceId()
                                        .equals(wl.getInstanceId()))
                                .findAny()
                                .orElse(null);
                        if (task != null) {
                            wl.setTaskName(task.getName());
                        }
                    }
            );
        }
        return annualReviewies;
    }

    @Override
    public int startDM(Map<String, Object> map) {
        String parentId = map.get("parentId")
                .toString();
        org.activiti.engine.runtime.ProcessInstance parentInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(parentId)
                .singleResult();
        Random random = new Random();
        int number = 0;
        for (int i = 0; i < 10; i++) {
            // 生成 0-9 随机整数
            number = random.nextInt(10);
            System.out.println("生成随机数：" + number);
            break;
        }
        String id = parentId+DateUtils.getDatehhmmss()+number;
        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("startDM")
                .withName(parentInstance.getName())
                .withBusinessKey(id)
                .withVariable("parentId", parentId)
                .build());

        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();

        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parentId);
        DealerNegativeInformationCheck dealerNegativeInformationCheck1 = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck1.setId(parentId);
        dealerNegativeInformationCheck1.setInstanceId(parentId);
        dealerNegativeInformationCheck1.setIsStartDM(true);
        if (null == dealerNegativeInformationCheck) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        } else {
            dealerNegativeInformationCheckService.updateDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        }

        //查询经销商
        BasicInformation basicInformationNew = new BasicInformation();
        List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(parentId);
        for (BasicInformation basicInformation : basicInformations) {
            BeanUtils.copyProperties(basicInformation, basicInformationNew);
            basicInformationNew.setInstanceId(id);
            basicInformationNew.setId(IdUtils.simpleUUID());
            basicInformationMapper.insertBasicInformation(basicInformationNew);
        }

        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(id);
        annualReviewy.setInstanceId(processInstance.getBusinessKey());
        annualReviewy.setTitle("startDM");
        annualReviewy.setType("startDM");  // TODO 待确认，先不填
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setState("0");
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        saveDbLog("1","新增流程",null ,processInstance.getBusinessKey(),null,annualReviewy,"问卷发送DM");


        //发送邮件
        try {
            org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
            org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                    .processInstanceId(processInstanceMe.getProcessInstanceId())
                    .singleResult();

            ThreadUtil.execute(new Runnable() {

                @Override
                public void run() {
                    actTaskService.sendMail(task1, parentId,null);
                }
            });

        } catch (Exception e) {
            log.error("邮件发送失败，{}",e.getMessage());
        }


        return 1;
    }

    @Override
    public int startPLM(Map<String, Object> map) {
        String parentId = map.get("parentId")
                .toString();
        org.activiti.engine.runtime.ProcessInstance parentInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceBusinessKey(parentId)
                .singleResult();
        String id = parentId+DateUtils.getDatehhmmss();

        Authentication.setAuthenticatedUserId(SecurityUtils.getLoginUser()
                .getUser()
                .getUserId()
                .toString());

        ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("startPLM")
                .withName(parentInstance.getName())
                .withBusinessKey(id)
                .withVariable("parentId", parentId)
                .build());
        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parentId);
        DealerNegativeInformationCheck dealerNegativeInformationCheck1 = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck1.setId(parentId);
        dealerNegativeInformationCheck1.setInstanceId(parentId);
        dealerNegativeInformationCheck1.setIsStartPLM(true);
        if (null == dealerNegativeInformationCheck) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        } else {
            dealerNegativeInformationCheckService.updateDealerNegativeInformationCheck(dealerNegativeInformationCheck1);
        }

        BasicInformation basicInformationNew = new BasicInformation();
        List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(parentId);
        for (BasicInformation basicInformation : basicInformations) {
            BeanUtils.copyProperties(basicInformation, basicInformationNew);
            basicInformationNew.setInstanceId(id);
            basicInformationNew.setId(IdUtils.simpleUUID());
            basicInformationMapper.insertBasicInformation(basicInformationNew);
        }

        AnnualReviewy annualReviewy = new AnnualReviewy();
        annualReviewy.setId(id);
        annualReviewy.setInstanceId(processInstance.getBusinessKey());
        annualReviewy.setTitle("startPLM");
        annualReviewy.setType("startPLM");  // TODO 待确认，先不填
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        annualReviewy.setState("0");
        annualReviewy.setCreateName(SecurityUtils.getNickName());
        annualReviewy.setCreateBy(SecurityUtils.getUsername());
        annualReviewy.setCreateTime(DateUtils.getNowDate());
        int i = annualReviewyMapper.insertAnnualReviewy(annualReviewy);
        saveDbLog("1","新增流程",null ,processInstance.getBusinessKey(),null,annualReviewy,"问卷发送PLM");



        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId())
                .singleResult();


        //发送邮件
        try {
            org.activiti.engine.runtime.ProcessInstance processInstanceMe = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(task.getProcessInstanceId())
                    .singleResult();
            // 上一个节点的执行完，再次查询，获取下一个节点的任务信息
            org.activiti.engine.task.Task task1 = taskService.createTaskQuery()
                    .processInstanceId(processInstanceMe.getProcessInstanceId())
                    .singleResult();

            ThreadUtil.execute(new Runnable() {

                @Override
                public void run() {
                    actTaskService.sendMail(task1, parentId,null);
                }
            });

        } catch (Exception e) {
            log.error("邮件发送失败，{}",e.getMessage());
        }

        return 1;
    }

    @Override
    public int dmSelect(Map<String, Object> map) {

        return 0;
    }

    @Override
    public Map<String, Object> selectAnnualReviewyByInstanceId  (String instanceId) throws Exception {

        Map<String, Object> map = new HashMap<>();  //一级
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        if (annualReviewy != null) {
            map.put("id", annualReviewy.getId()); // id
            map.put("instanceId", annualReviewy.getInstanceId()); // instanceId
            map.put("title", annualReviewy.getTitle()); // 标题
            map.put("createTime", annualReviewy.getCreateTime()); // 创建时间
            map.put("createName", annualReviewy.getCreateName()); // 发起人中午名称
            map.put("createBy", annualReviewy.getCreateBy()); // 发起人用户名称
            map.put("approvalName",annualReviewy.getApprovalName());
            //map.put("lockname", annualReviewy.getLockname()); // 任务拾取人
        }
        Map<String, Object> data = new HashMap<>();  // 二级
        List<Map<String, Object>> childrenList = new ArrayList();
        List<String> dealernameList = new ArrayList<>();
        Map<String, Object> groupName = new HashMap<>();
        List<BasicInformation> basicInformationList = basicInformationMapper.selectDealerGroupByByInstanceId(instanceId);
        if (basicInformationList != null && basicInformationList.size() > 0) {
            for (BasicInformation basicInformation : basicInformationList) {
                Map<String, Object> children = new HashMap<>();
                if(null != basicInformation.getDealerNameCN() && !(basicInformation.getDealerNameCN().equals(""))){
                    dealernameList.add(basicInformation.getDealerNameCN());
                }
                groupName.put("groupNameEN", basicInformation.getGroupNameEN()); // groupNameEN
                groupName.put("groupNameCN", basicInformation.getGroupNameCN()); // groupNameCN

                children.put("basicInformationId", basicInformation.getId());
                children.put("instanceId", basicInformation.getInstanceId());
                children.put("gm", basicInformation.getGm());
                children.put("dealerCodeFromManufacturer", basicInformation.getDealerCodeFromManufacturer());
                children.put("dealerCodeFromWFS", basicInformation.getDealerCodeFromWFS());
                children.put("dealerNameCN", basicInformation.getDealerNameCN());
                children.put("dealerNameEN", basicInformation.getDealerNameEN());
                children.put("dealername", basicInformation.getDealername());
                children.put("incorporationDate", basicInformation.getIncorporationDate());
                children.put("joinSectorDealerNetworkDate", basicInformation.getJoinSectorDealerNetworkDate());
                children.put("paidupCapital", basicInformation.getPaidupCapital());
                children.put("province", basicInformation.getProvince());
                children.put("relatedWorkingExperience", basicInformation.getRelatedWorkingExperience());
                children.put("value", basicInformation.getDealerValue());
                children.put("registeredCapital", basicInformation.getRegisteredCapital());
                children.put("registeredAddressCN", basicInformation.getRegisteredAddressCN());
                children.put("registeredAddressEN", basicInformation.getRegisteredAddressEN());
                children.put("legalRepresentativeEN", basicInformation.getLegalRepresentativeEN());
                children.put("legalRepresentativeCN", basicInformation.getLegalRepresentativeCN());
                if (null != basicInformation.getSector()) {
                    String[] split = basicInformation.getSector().split(",");
                    children.put("sector", split);
                }
                ArrayList<Map<String, Object>> shareholdersAndShare = new ArrayList<>();
                if (null != basicInformation.getShareholders()) {
                    String[] shareholderStrs = basicInformation.getShareholders().split("#");
                    if(shareholderStrs==null){
                        String[] share = basicInformation.getShareholders().split("\\$\\|");
                        Map<String, Object> tmpObj = new HashMap<String, Object>();
                        if(share.length == 3){
                            tmpObj.put("shareholdersCn", ObjectUtil.isEmpty(share[0])?"":share[0]);
                            tmpObj.put("shareholdersEn",ObjectUtil.isEmpty(share[1])?"":share[1]);
                            tmpObj.put("share",ObjectUtil.isEmpty(share[2])?"":share[2]);
                        }
                        shareholdersAndShare.add(tmpObj);
                    }else{
                        for (String shareholderStr : shareholderStrs) {
                            String[] share = shareholderStr.split("\\$\\|");
                            Map<String, Object> tmpObj = new HashMap<String, Object>();
                            if(share.length == 3){
                                tmpObj.put("shareholdersCn", ObjectUtil.isEmpty(share[0])?"":share[0]);
                                tmpObj.put("shareholdersEn",ObjectUtil.isEmpty(share[1])?"":share[1]);
                                tmpObj.put("share",ObjectUtil.isEmpty(share[2])?"":share[2]);
                            }
                            shareholdersAndShare.add(tmpObj);
                        }
                    }

                    children.put("shareholdersAndShare", shareholdersAndShare);
                }
                childrenList.add(children);
            }
        }
        data.put("groupName", groupName); // groupNameEN

//        List<SalesPerformanceAndTargetVO> salesPerformanceAndTargetVOS = new ArrayList<>();
//        List<SalesPerformanceAndTarget> salesPerformanceAndTargetList = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(instanceId);
//        if (salesPerformanceAndTargetList != null && salesPerformanceAndTargetList.size() > 0) {
//            data.put("sales_performance_and_target", salesPerformanceAndTargetList);
//        }

//        List<LimitCalculationForCommericalNeedVO> limitCalculationForCommericalNeedVOS = new ArrayList<>();
//
//        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeedList = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(instanceId);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();

        List<String> dname = new ArrayList<String>();
        for(BasicInformation lcfcn : basicInformationList){
            String dealername = lcfcn.getDealerNameCN();
            dname.add(dealername);
        }
        List<String> listTemp = new ArrayList<String>();
        for (int i = 0; i < dname.size(); i++) {
            if (!listTemp.contains(dname.get(i))) {
                listTemp.add(dname.get(i));
            }
        }
        objectObjectHashMap.put("instanceId", instanceId);
        objectObjectHashMap.put("dealerName", listTemp);
        List<Map<String, Object>> maps = this.approvalLimitCalculationForCommericalNeeds(objectObjectHashMap);
        if (maps != null && maps.size() > 0) {
            data.put("limit_calculation_for_commerical_needs", maps);
        }

        List<Map<String, Object>> maps1 = this.listWprvoApproval(objectObjectHashMap);
        if (maps1 != null && maps1.size() > 0) {
            data.put("WholesalePerformanceOS", maps1);
        }

        List<Map<String, Object>> maps2 = this.listspatApproval(objectObjectHashMap);
        if (maps2 != null && maps2.size() > 0) {
            data.put("sales_performance_and_target", maps2);
        }

        List<Map<String, Object>> maps3 = this.selectplmWhereDealerName(listTemp);
        if (maps3 != null && maps3.size() > 0) {
            data.put("stock", maps3);
        }
        List<String> dealerNamess = creditConditionMapper.listByInstanceId1(instanceId);
        ArrayList<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS1 = new ArrayList<>();
        if (dealerNamess.size() > 0) {
            for (String dealerNames : dealerNamess) {
                List<CreditCondition> creditConditions = creditConditionMapper.listByInstanceId2(instanceId, dealerNames);
                ThirdCreditInfoSimpleVO thirdCreditInfoSimpleVO = new ThirdCreditInfoSimpleVO();
                ArrayList<ThirdCreditInfoSimpleChild> childArrayList = new ArrayList<>();
                for (CreditCondition creditCondition : creditConditions) {
                    ThirdCreditInfoSimpleChild thirdCreditInfoSimpleChild = new ThirdCreditInfoSimpleChild();
                    thirdCreditInfoSimpleVO.setDealerId(creditCondition.getDealerid());
                    thirdCreditInfoSimpleVO.setDealerName(creditCondition.getDealername());
                    thirdCreditInfoSimpleChild.setDealerId(creditCondition.getDealerid());
                    thirdCreditInfoSimpleChild.setDealerName(creditCondition.getDealername());
                    thirdCreditInfoSimpleChild.setSector(creditCondition.getSector());
                    thirdCreditInfoSimpleChild.setLimitType(creditCondition.getLimittype());
                    thirdCreditInfoSimpleChild.setExpiryDate(creditCondition.getExpireddate());
                    thirdCreditInfoSimpleChild.setBuyBack(creditCondition.getBuyback());
                    thirdCreditInfoSimpleChild.setLoanTenor(creditCondition.getLoantenor());
                    thirdCreditInfoSimpleChild.setReviewType(creditCondition.getReviewtype());
                    childArrayList.add(thirdCreditInfoSimpleChild);
                }
                if(childArrayList!=null && childArrayList.size()>0 ){
                    for (ThirdCreditInfoSimpleChild  chi : childArrayList) {
                        chi.setSort(DayUtils.typeSort(chi.getLimitType()));
                    }
                    Collections.sort(childArrayList, new Comparator<ThirdCreditInfoSimpleChild>() {
                        @Override
                        public int compare(ThirdCreditInfoSimpleChild o1, ThirdCreditInfoSimpleChild o2) {
                            return o1.getSort().compareTo(o2.getSort());
                        }

                        @Override
                        public boolean equals(Object obj) {
                            return false;
                        }
                    });
                    Collections.sort(childArrayList, new Comparator<ThirdCreditInfoSimpleChild>() {
                        @Override
                        public int compare(ThirdCreditInfoSimpleChild o1, ThirdCreditInfoSimpleChild o2) {
                            return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                        }

                        @Override
                        public boolean equals(Object obj) {
                            return false;
                        }
                    });
                }
                thirdCreditInfoSimpleVO.setChild(childArrayList);
                thirdCreditInfoSimpleVOS1.add(thirdCreditInfoSimpleVO);
            }
/*            List<String> names = creditConditions.stream().map(CreditCondition::getDealername).distinct().collect(Collectors.toList());
            List<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS = creditConditionService.thirdCreditResult(names);
            for (ThirdCreditInfoSimpleVO t : thirdCreditInfoSimpleVOS) {
                for (ThirdCreditInfoSimpleChild r : t.getChild()) {
                    for (CreditCondition c : creditConditions) {
                        if (r.getDealerName().equals(c.getDealername()) && r.getSector().equals(c.getSector()) && r.getLimitType().equals(c.getLimittype())) {
                            if (r.getExpiryDate() == null) {
                                r.setExpiryDate(c.getExpireddate());
                            }
                            r.setReviewType(c.getReviewtype());
                            r.setLoanTenor(c.getLoantenor());
                            r.setBuyBack(c.getBuyback());
                            r.setId(c.getId());
                        }
                    }
                    ;
                }
                ;
            }
            ;*/

            data.put("credit_condition", thirdCreditInfoSimpleVOS1);
        }


        List<WholesalePerformanceCurrently> wholesalePerformanceCurrentlys = new ArrayList<>();
        wholesalePerformanceCurrentlys = wholesalePerformanceCurrentlyMapper.selectWholesalePerformanceCurrentlyByInstanceId(instanceId);
        if (wholesalePerformanceCurrentlys != null && wholesalePerformanceCurrentlys.size() > 0) {
            for (WholesalePerformanceCurrently who : wholesalePerformanceCurrentlys) {
                who.setSort(DayUtils.typeSort(who.getLimitType()));
            }
            Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                @Override
                public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                    return o1.getSort().compareTo(o2.getSort());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                @Override
                public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                    return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });

            Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                @Override
                public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                    return o1.getDealername().compareTo(o2.getDealername());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            data.put("WholesalePerformanceCurrent", wholesalePerformanceCurrentlys);
        }

        List<OtherFinancingResourceVO> otherFinancingResourceVOS = new ArrayList<>();
        if(dealernameList !=null && dealernameList.size()>0 ){
            List<OtherFinancingResource> otherFinancingResourceList = otherFinancingResourceMapper.selectOtherFinancingResourceBydealername(dealernameList);
            if (otherFinancingResourceList != null && otherFinancingResourceList.size() > 0) {
                data.put("other_financing_resource", otherFinancingResourceList);
            }
        }


        List<TemporaryConditionFollowUp> temporaryConditionFollowUpList = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByDealername(dealernameList);
        if (temporaryConditionFollowUpList != null && temporaryConditionFollowUpList.size() > 0) {
            data.put("temporary_condition_follow_up", temporaryConditionFollowUpList);
        }
        HBasicCorporateGuarantee hBasicCorporateGuarantee = new HBasicCorporateGuarantee();
        hBasicCorporateGuarantee.setInstanceid(instanceId);
        List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeListByName(hBasicCorporateGuarantee);
        if (hBasicCorporateGuarantees != null && hBasicCorporateGuarantees.size() > 0) {
            ArrayList<Object> objects = new ArrayList<>();
            for (HBasicCorporateGuarantee basicCorporateGuarantee : hBasicCorporateGuarantees) {
                Map<String, Object> GuaranteeInfoData = new HashMap<>();  // 三级
                GuaranteeInfoData.put("dealername",basicCorporateGuarantee.getDealername());

                HBasicCorporateGuarantee hBasicCorporateGuarantee2 = new HBasicCorporateGuarantee();
                hBasicCorporateGuarantee2.setInstanceid(instanceId);
                hBasicCorporateGuarantee2.setDealername(basicCorporateGuarantee.getDealername());
                List<HBasicCorporateGuarantee> hBasicCorporateGuarantees1 = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeList(hBasicCorporateGuarantee2);
                GuaranteeInfoData.put("GuaranteeInfo", hBasicCorporateGuarantees1);
                //查询另外一个
                HBasicCorporate hBasicCorporate2 = new HBasicCorporate();
                hBasicCorporate2.setInstanceid(instanceId);
                hBasicCorporate2.setDealername(basicCorporateGuarantee.getDealername());
                List<HBasicCorporate> hBasicCorporates1 = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate2);
                GuaranteeInfoData.put("CorporateInfo", hBasicCorporates1);
                objects.add(GuaranteeInfoData);
            }

            data.put("GuaranteeInfoDate", objects);
        }

        List<LoyaltyPerformance4q> loyaltyPerformance4qUpList = loyaltyPerformance4qMapper.selectLoyaltyPerformance4qByInstanceId(instanceId);
        if (loyaltyPerformance4qUpList != null && loyaltyPerformance4qUpList.size() > 0) {
            data.put("loyalty_performance_4q", loyaltyPerformance4qUpList);
        }

        List<LoyaltyPerformance6month> loyaltyPerformance6monthUpList = loyaltyPerformance6monthMapper.selectLoyaltyPerformance6monthByInstanceId(instanceId);
        if (loyaltyPerformance6monthUpList != null && loyaltyPerformance6monthUpList.size() > 0) {
            data.put("loyalty_performance_6month", loyaltyPerformance6monthUpList);
        }

        List<String> loyalty_performance_6month_hearders_result = new ArrayList<>();
        loyalty_performance_6month_hearders_result.add("Item");
        loyalty_performance_6month_hearders_result.add("Dealer");
        loyalty_performance_6month_hearders_result.add("Sector");
        List<String> loyalty_performance_6month_hearders = loyaltyPerformance6monthMapper.selectLoyaltyPerformance6monthHeardersByInstanceId(instanceId);
        if (loyalty_performance_6month_hearders != null && loyalty_performance_6month_hearders.size() > 0) {
            loyalty_performance_6month_hearders_result.addAll(loyalty_performance_6month_hearders);
            data.put("loyalty_performance_6month_hearders", loyalty_performance_6month_hearders_result);
        }

        List<ProposalByCommericalAndMarketingVO> proposalByCommericalAndMarketingVOS = new ArrayList<>();
        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingList = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(instanceId);
        if (proposalByCommericalAndMarketingList != null && proposalByCommericalAndMarketingList.size() > 0) {
            for (ProposalByCommericalAndMarketing pro : proposalByCommericalAndMarketingList) {
                pro.setSort(DayUtils.typeSort(pro.getLimitType()));
            }
            Collections.sort(proposalByCommericalAndMarketingList, new Comparator<ProposalByCommericalAndMarketing>() {
                @Override
                public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                    return o1.getSort().compareTo(o2.getSort());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            Collections.sort(proposalByCommericalAndMarketingList, new Comparator<ProposalByCommericalAndMarketing>() {
                @Override
                public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                    return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });

            Collections.sort(proposalByCommericalAndMarketingList, new Comparator<ProposalByCommericalAndMarketing>() {
                @Override
                public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                    return o1.getDealername().compareTo(o2.getDealername());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            data.put("proposal_by_commerical_and_marketing", proposalByCommericalAndMarketingList);
        }

        List<Grade> gradeList = gradeService.selectGradeByInstanceId(instanceId);
        if (gradeList != null && gradeList.size() > 0) {
            data.put("grade", gradeList);
        }
        ActiveLimitAdjustmentProposal proposalParam = new ActiveLimitAdjustmentProposal();
        proposalParam.setInstanceId(instanceId);
        List<ActiveLimitAdjustmentProposal> proposalList = activeLimitAdjustmentProposalMapper.selectActiveLimitAdjustmentProposalList(proposalParam);
        if (proposalList != null && proposalList.size() > 0) {
            for (ActiveLimitAdjustmentProposal proposal : proposalList) {
                proposal.setSort(DayUtils.typeSort(proposal.getLimitType()));
                if(proposal.getDeposit() ==null || proposal.getDeposit().equals("null")){
                    proposal.setDeposit("");
                }
            }
            Collections.sort(proposalList, new Comparator<ActiveLimitAdjustmentProposal>() {
                @Override
                public int compare(ActiveLimitAdjustmentProposal o1, ActiveLimitAdjustmentProposal o2) {
                    return o1.getSort().compareTo(o2.getSort());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            Collections.sort(proposalList, new Comparator<ActiveLimitAdjustmentProposal>() {
                @Override
                public int compare(ActiveLimitAdjustmentProposal o1, ActiveLimitAdjustmentProposal o2) {
                    return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });

            Collections.sort(proposalList, new Comparator<ActiveLimitAdjustmentProposal>() {
                @Override
                public int compare(ActiveLimitAdjustmentProposal o1, ActiveLimitAdjustmentProposal o2) {
                    return o1.getDealerName().compareTo(o2.getDealerName());
                }

                @Override
                public boolean equals(Object obj) {
                    return false;
                }
            });
            data.put("active_limit_adjustment_proposal", proposalList);
        }

        List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingBySubProcessId(instanceId);
        if (dealercodeContractFilings != null && dealercodeContractFilings.size() > 0) {
            data.put("contract_sub_process_list", dealercodeContractFilings);
        }
       /* HAml hAml = new HAml();
        hAml.setInstanceId(instanceId);
        List<HAml> AM = amlMapper.selectHAmlList(hAml);
        data.put("aml", AM);*/

        CbFleetDetails cbFleetDetails = new CbFleetDetails();
        cbFleetDetails.setInstanceId(instanceId);
        List<CbFleetDetails> cbfleetDetailsList = cbFleetDetailsMapper.selectCbFleetDetailsList(cbFleetDetails);
        data.put("cb_fleet_details", cbfleetDetailsList);

        BalanceInformation balanceInformation = new BalanceInformation();
        balanceInformation.setInstanceId(instanceId);
        List<BalanceInformation> balanceInformationList = balanceInformationMapper.selectBalanceInformationList(balanceInformation);
        data.put("balance_information", balanceInformationList);
        List<SecuritieVO> securitieVOS = new ArrayList<>();
        List<Securities> securitieList = securitiesMapper.selectSecuritiesByInstanceId(instanceId);
        LinkedHashSet<String> dealerNames = new LinkedHashSet<>();
        for (int i = 0; i < basicInformationList.size(); i++) {
            dealerNames.add(basicInformationList.get(i).getDealerNameCN());
        }
        List<String> dealers = new ArrayList<>(dealerNames);
        for (String dealer : dealers) {
            SecuritieVO securitieVO = new SecuritieVO();
            securitieVO.setDealername(dealer);
            securitieVOS.add(securitieVO);
        }
        if (securitieList != null && securitieList.size() > 0) {
            for (int j = 0; j < securitieList.size(); j++) {
                Securities securities = securitieList.get(j);
                for (int i = 0; i < securitieVOS.size(); i++) {
                    SecuritieVO securitieVO = securitieVOS.get(i);
                    if (securitieVO.getDealername().equals(securities.getDealername())) {
                        if (null == securitieVO.getChildren()) {
                            securitieVO.setChildren(new ArrayList<Securities>());
                        }
                        securitieVO.getChildren().add(securities);
                    }
                }
            }
        }
        //刷新按钮
        List<HistoricTaskInstance> taskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).list();

        for (HistoricTaskInstance his : taskInstance) {
            if(his.getName().equals("合同修改") && his.getAssignee() == null  && his.getEndTime() == null){
                //刷新
                data.put("refresh","show");
            }else {
                //刷新
                data.put("refresh","on");
            }
        }

        data.put("securities", securitieVOS);


        List<TemporaryConditionFollowUp> temporaryConditionFollowUp = temporaryConditionFollowUpMapper.selectTemporaryConditionFollowUpByInstanceId(instanceId);
        if (null != temporaryConditionFollowUp) {
            map.put("temporaryConditionFollowUp", temporaryConditionFollowUp);
        }

        DealerNegativeInformationCheck dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(instanceId);
        if (null != dealerNegativeInformationCheck) {
            map.put("dealerNegativeInformationCheck", dealerNegativeInformationCheck);
        }

        Fileupload fileupload = new Fileupload();
        fileupload.setInstanceId(instanceId);
        fileupload.setType("application");
        List<Fileupload> application = fileuploadService.selectFileuploadList(fileupload);
        if (application != null) {
            map.put("application", application);
        }

        Fileupload file = new Fileupload();
        fileupload.setInstanceId(instanceId);
        fileupload.setType("contractSubprocess");
        List<Fileupload> fileuploads = fileuploadService.selectFileuploadList(fileupload);
        if (CollectionUtil.isNotEmpty(fileuploads)) {
            map.put("contractSubprocess", file);
        }

        fileupload.setType("information");
        List<Fileupload> information = fileuploadService.selectFileuploadList(fileupload);
        if (information != null) {
            map.put("information", information);
        }
        fileupload.setType("financials");
        List<Fileupload> financials = fileuploadService.selectFileuploadList(fileupload);
        if (financials != null) {
            map.put("financials", financials);
        }
        fileupload.setType("guarantee");
        List<Fileupload> guarantee = fileuploadService.selectFileuploadList(fileupload);
        if (guarantee != null) {
            map.put("guarantee", guarantee);
        }
        fileupload.setType("corporate");
        List<Fileupload> corporate = fileuploadService.selectFileuploadList(fileupload);
        if (corporate != null) {
            map.put("corporate", corporate);
        }
        fileupload.setType("other");
        List<Fileupload> other = fileuploadService.selectFileuploadList(fileupload);
        if (other != null) {
            map.put("other", other);
        }
        fileupload.setType("financialAnalysis");
        List<Fileupload> financialAnalysis = fileuploadService.selectFileuploadList(fileupload);
        if (financialAnalysis != null) {
            map.put("financialAnalysis", financialAnalysis);
        }
        fileupload.setType("pboc");
        List<Fileupload> pboc = fileuploadService.selectFileuploadList(fileupload);
        if (pboc != null) {
            map.put("pboc", pboc);
        }
        fileupload.setType("lawsuit");
        List<Fileupload> lawsuit = fileuploadService.selectFileuploadList(fileupload);
        if (lawsuit != null) {
            map.put("lawsuit", lawsuit);
        }
        fileupload.setType("underwriterOther");
        List<Fileupload> underwriterOther = fileuploadService.selectFileuploadList(fileupload);
        if (underwriterOther != null) {
            map.put("underwriterOther", underwriterOther);
        }
        fileupload.setType("opDocument");
        List<Fileupload> opDocument = fileuploadService.selectFileuploadList(fileupload);
        if (opDocument != null) {
            map.put("opDocument", opDocument);
        }
        fileupload.setType("opDocumentFax");
        List<Fileupload> opDocumentFax = fileuploadService.selectFileuploadList(fileupload);
        if (opDocumentFax != null) {
            map.put("opDocumentFax", opDocumentFax);
        }

       /* if (null == annualReviewy.getLockname()) {
            String username = SecurityUtils.getLoginUser().getUsername();
            annualReviewyMapper.closeUpdateAnnualReviewyObj(instanceId, username);
        }*/
        data.put("children", childrenList);

        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);
        if (notes != null) {
            data.put("basicNotes", notes.getBasicNotes());
            data.put("dealerNotes", notes.getDealerNotes());
            data.put("loyaltyNotes", notes.getLoyaltyNotes());
            data.put("auditNotes", notes.getAuditNotes());
            data.put("wholesaleNotes", notes.getWholesaleNotes());
            data.put("proposalNotes", notes.getProposalNotes());
            data.put("creditComments", notes.getCreditComments());
            data.put("guaranteeNotes", notes.getGuaranteeNotes());
            data.put("amlNotes", notes.getAmlNotes());
            data.put("comments", notes.getComments());
            data.put("conditionNotes", notes.getConditionNotes());

        }
        //子流程也要查询主流程的信息
        if(instanceId.contains("-")){
            String[] split = instanceId.split("-");
            List<SecuritieVO> securitieVOSTemp = new ArrayList<>();
            List<Securities> securitieListTemp = securitiesMapper.selectSecuritiesByInstanceId(split[0]);
            LinkedHashSet<String> dealerNamesTemp = new LinkedHashSet<>();
            for (Securities securities : securitieListTemp) {
                String dealername = securities.getDealername();
                dealerNamesTemp.add(dealername);
            }
            List<String> dealersTemp = new ArrayList<>(dealerNamesTemp);
            for (String dealer : dealersTemp) {
                SecuritieVO securitieVO = new SecuritieVO();
                securitieVO.setDealername(dealer);
                securitieVOSTemp.add(securitieVO);
            }
            if (securitieListTemp != null && securitieListTemp.size() > 0) {
                for (int j = 0; j < securitieListTemp.size(); j++) {
                    Securities securities = securitieListTemp.get(j);
                    for (int i = 0; i < securitieVOSTemp.size(); i++) {
                        SecuritieVO securitieVO = securitieVOSTemp.get(i);
                        if (securitieVO.getDealername().equals(securities.getDealername())) {
                            if (null == securitieVO.getChildren()) {
                                securitieVO.setChildren(new ArrayList<Securities>());
                            }
                            securitieVO.getChildren().add(securities);
                        }
                    }
                }
            }
            data.put("securities", securitieVOSTemp);

            List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketingListTemp = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(split[0]);
            if (proposalByCommericalAndMarketingListTemp != null && proposalByCommericalAndMarketingListTemp.size() > 0) {
                for (ProposalByCommericalAndMarketing pro : proposalByCommericalAndMarketingListTemp) {
                    pro.setSort(DayUtils.typeSort(pro.getLimitType()));
                }
                Collections.sort(proposalByCommericalAndMarketingListTemp, new Comparator<ProposalByCommericalAndMarketing>() {
                    @Override
                    public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                        return o1.getSort().compareTo(o2.getSort());
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });
                Collections.sort(proposalByCommericalAndMarketingListTemp, new Comparator<ProposalByCommericalAndMarketing>() {
                    @Override
                    public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                        return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });

                Collections.sort(proposalByCommericalAndMarketingListTemp, new Comparator<ProposalByCommericalAndMarketing>() {
                    @Override
                    public int compare(ProposalByCommericalAndMarketing o1, ProposalByCommericalAndMarketing o2) {
                        return o1.getDealername().compareTo(o2.getDealername());
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });
                data.put("proposal_by_commerical_and_marketing", proposalByCommericalAndMarketingListTemp);
            }

            wholesalePerformanceCurrentlys = wholesalePerformanceCurrentlyMapper.selectWholesalePerformanceCurrentlyByInstanceId(split[0]);
            if (wholesalePerformanceCurrentlys != null && wholesalePerformanceCurrentlys.size() > 0) {
                for (WholesalePerformanceCurrently who : wholesalePerformanceCurrentlys) {
                    who.setSort(DayUtils.typeSort(who.getLimitType()));
                }
                Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                    @Override
                    public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                        return o1.getSort().compareTo(o2.getSort());
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });
                Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                    @Override
                    public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                        return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });

                Collections.sort(wholesalePerformanceCurrentlys, new Comparator<WholesalePerformanceCurrently>() {
                    @Override
                    public int compare(WholesalePerformanceCurrently o1, WholesalePerformanceCurrently o2) {
                        return o1.getDealername().compareTo(o2.getDealername());
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });
                data.put("WholesalePerformanceCurrent", wholesalePerformanceCurrentlys);
            }

            List<String> dealerNamessTemp = creditConditionMapper.listByInstanceId1(split[0]);
            ArrayList<ThirdCreditInfoSimpleVO> thirdCreditInfoSimpleVOS2 = new ArrayList<>();
            if (dealerNamessTemp.size() > 0) {
                for (String dealerNames1 : dealerNamessTemp) {
                    List<CreditCondition> creditConditions = creditConditionMapper.listByInstanceId2(split[0], dealerNames1);
                    ThirdCreditInfoSimpleVO thirdCreditInfoSimpleVO = new ThirdCreditInfoSimpleVO();
                    ArrayList<ThirdCreditInfoSimpleChild> childArrayList = new ArrayList<>();
                    for (CreditCondition creditCondition : creditConditions) {
                        ThirdCreditInfoSimpleChild thirdCreditInfoSimpleChild = new ThirdCreditInfoSimpleChild();
                        thirdCreditInfoSimpleVO.setDealerId(creditCondition.getDealerid());
                        thirdCreditInfoSimpleVO.setDealerName(creditCondition.getDealername());
                        thirdCreditInfoSimpleChild.setDealerId(creditCondition.getDealerid());
                        thirdCreditInfoSimpleChild.setDealerName(creditCondition.getDealername());
                        thirdCreditInfoSimpleChild.setSector(creditCondition.getSector());
                        thirdCreditInfoSimpleChild.setLimitType(creditCondition.getLimittype());
                        thirdCreditInfoSimpleChild.setExpiryDate(creditCondition.getExpireddate());
                        thirdCreditInfoSimpleChild.setBuyBack(creditCondition.getBuyback());
                        thirdCreditInfoSimpleChild.setLoanTenor(creditCondition.getLoantenor());
                        thirdCreditInfoSimpleChild.setReviewType(creditCondition.getReviewtype());
                        childArrayList.add(thirdCreditInfoSimpleChild);
                    }
                    if(childArrayList!=null && childArrayList.size()>0 ){
                        for (ThirdCreditInfoSimpleChild  chi : childArrayList) {
                            chi.setSort(DayUtils.typeSort(chi.getLimitType()));
                        }
                        Collections.sort(childArrayList, new Comparator<ThirdCreditInfoSimpleChild>() {
                            @Override
                            public int compare(ThirdCreditInfoSimpleChild o1, ThirdCreditInfoSimpleChild o2) {
                                return o1.getSort().compareTo(o2.getSort());
                            }

                            @Override
                            public boolean equals(Object obj) {
                                return false;
                            }
                        });
                        Collections.sort(childArrayList, new Comparator<ThirdCreditInfoSimpleChild>() {
                            @Override
                            public int compare(ThirdCreditInfoSimpleChild o1, ThirdCreditInfoSimpleChild o2) {
                                return o1.getSector().substring(0).compareTo(o2.getSector().substring(0));
                            }

                            @Override
                            public boolean equals(Object obj) {
                                return false;
                            }
                        });
                    }
                    thirdCreditInfoSimpleVO.setChild(childArrayList);
                    thirdCreditInfoSimpleVOS2.add(thirdCreditInfoSimpleVO);
                }
                data.put("credit_condition", thirdCreditInfoSimpleVOS2);
            }
            //查询法人变更信息
            List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceId(split[0]);
            if(basicInformations != null && basicInformations.size()>0){
                List<Map<String, String>> listMap = new ArrayList<>();
                for (BasicInformation basicInformation : basicInformations) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("dealerNameCN",basicInformation.getDealerNameCN());
                    hashMap.put("outLegalRepresentativeCN",basicInformation.getOutLegalRepresentativeCN());
                    hashMap.put("newLegalRepresentativeCN",basicInformation.getNewLegalRepresentativeCN());
                    listMap.add(hashMap);
                }
                data.put("legal_person_info", listMap);
            }
            AnnualReviewy annualReviewyTemp = annualReviewyMapper.selectAnnualReviewyByInstanceId(split[0]);
            if(annualReviewyTemp!=null){
                data.put("uwApprovalName", annualReviewyTemp.getUwApprovalName());
            }
            //查询是否有作废的历史 先查询经销商品牌额度类型
            AnnualReviewy sonContractInfo = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
            //先查询自己的那一条确认时间
            DealercodeContractFiling dealercodeContractFiling1 = new DealercodeContractFiling();
            dealercodeContractFiling1.setSubProcessId(instanceId);
            List<DealercodeContractFiling> dealercodeContractFilings1 = dealercodeContractFilingMapper.selectDealercodeContractFilingList(dealercodeContractFiling1);
            Date rcIssueDate = null;
            if(dealercodeContractFilings1!=null && dealercodeContractFilings1.size()>0){
                DealercodeContractFiling dealercodeContractFiling = dealercodeContractFilings1.get(0);
                if(dealercodeContractFiling!=null && dealercodeContractFiling.getRcIssueDate()!=null){
                    rcIssueDate = dealercodeContractFiling.getRcIssueDate();
                }
            }
            if(sonContractInfo!=null && sonContractInfo.getDealerName()!=null  && sonContractInfo.getSector()!=null && sonContractInfo.getLimitType()!=null && rcIssueDate !=null){
                DealercodeContractFiling dealercodeContractFiling = new DealercodeContractFiling();
                dealercodeContractFiling.setDealerNameCN(sonContractInfo.getDealerName());
                dealercodeContractFiling.setSector(sonContractInfo.getSector());
                dealercodeContractFiling.setLimitType(sonContractInfo.getLimitType());
                dealercodeContractFiling.setRcIssueDate(rcIssueDate);
                List<DealercodeContractFiling> contractS = dealercodeContractFilingMapper.selectDealercodeContractFilingByMax(dealercodeContractFiling);
                if(contractS!=null && contractS.size()>0){
                    DealercodeContractFiling contractFiling = contractS.get(0);
                    if(contractFiling.getStatus()!=null&&"1".equals(contractFiling.getStatus())){
                        //说明作废了 查询主合同号
                        DealercodeContract dealercodeContract = new DealercodeContract();
                        dealercodeContract.setInstanceId(contractFiling.getInstanceId());
                        dealercodeContract.setDealerNameCN(contractFiling.getDealerNameCN());
                        dealercodeContract.setSector(contractFiling.getSector());
                        dealercodeContract.setLimitType(contractFiling.getLimitType());
                        List<DealercodeContract> dealercodeContracts = dealercodeContractMapper.selectDealercodeContractByCancel(dealercodeContract);
                        if(dealercodeContracts!=null && dealercodeContracts.size()>0){
                            for (DealercodeContract contract : dealercodeContracts) {
                                if(contract.getContract()!=null){
                                    String[] contractNo = contract.getContract().split("-");
                                    data.put("isShow", 1);
                                    data.put("contract",contractNo[0]);
                                    System.out.println("123"+contractNo[0]);
                                    break;
                                }
                            }
                            if(data.get("isShow")==null){
                                data.put("isShow", 0);
                            }
                        }else{
                            //没有作废
                            data.put("isShow", 0);
                        }
                    }else{
                        //没有作废
                        data.put("isShow", 0);
                    }
                }
            }

        }
        map.put("data", data);
        return map;
    }

    @Override
    public Map<String,Object> getCorporateGuarantee(String instanceId) {
        Map<String, Object> data = new HashMap<>();  // 二级
        Map<String, Object> map = new HashMap<>();  //一级
        HBasicCorporateGuarantee hBasicCorporateGuarantee = new HBasicCorporateGuarantee();
        hBasicCorporateGuarantee.setInstanceid(instanceId);
        List<HBasicCorporateGuarantee> hBasicCorporateGuarantees = basicCorporateGuaranteeMapper.selectHBasicCorporateGuaranteeList(hBasicCorporateGuarantee);
        if (hBasicCorporateGuarantees != null && hBasicCorporateGuarantees.size() > 0) {
            data.put("GuaranteeInfo", hBasicCorporateGuarantees);
        }
        HBasicCorporate hBasicCorporate = new HBasicCorporate();
        hBasicCorporate.setInstanceid(instanceId);
        List<HBasicCorporate> hBasicCorporates = basicCorporateMapper.selectHBasicCorporateList(hBasicCorporate);
        if (hBasicCorporates != null && hBasicCorporates.size() > 0) {
            data.put("CorporateInfo", hBasicCorporates);
        }
        map.put("data", data);
        return map;
    }

    @Override
    public Map<String,Object> selectAnnualReviewyinfo(String instanceId) {
        String firstName ="";
        String firsttaskNodeName ="";
        String firstDate ="";
        HashMap<String, Object> map = new HashMap<>();
        AnnualReviewy annualReviewy = annualReviewyMapper.selectAnnualReviewyByInstanceId(instanceId);
        if(annualReviewy != null && annualReviewy.getState() !=null && !(annualReviewy.getState().equals("3")) ){
            if(annualReviewy != null){
                firstName = annualReviewy.getCreateName();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                firstDate = sdf.format(annualReviewy.getCreateTime());
            }
            HistoricProcessInstance procInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
            List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processDefinitionId(procInstance.getProcessDefinitionId()).orderByHistoricTaskInstanceStartTime().asc().list();
            if(list.size()>0 && list !=null){
                HistoricTaskInstance historicTaskInstance = list.get(0);
                firsttaskNodeName = historicTaskInstance.getName();
            }
        }
        map.put("firstName",firstName);
        map.put("firsttaskNodeName",firsttaskNodeName);
        map.put("firstDate",firstDate);
        return map;
    }

    /**
     * 根据id查询，给邮箱模板返回需要的信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> selectMailInfoById(String id) {
        ApprovedLimitAndCondition approvedLimitAndCondition = approvedLimitAndConditionMapper.selectApprovedLimitAndConditionById(id);
        CreditCondition creditCondition = creditConditionMapper.selectCreditConditionById(id);
        BasicInformation basicInformation = basicInformationMapper.selectBasicInformationById(id);

        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("DealerNameEN", basicInformation.getDealerNameEN());
        mailMap.put("DealerNameCN", basicInformation.getDealerNameCN());
        mailMap.put("sector", basicInformation.getSector());
        mailMap.put("current_year", "");
        mailMap.put("limit", approvedLimitAndCondition.getLimittype());
        mailMap.put("deposit", approvedLimitAndCondition.getApprovedcashdeposit());
        mailMap.put("guarantee_structure", "");
        mailMap.put("approvedLimitAndCondition", approvedLimitAndCondition);
        mailMap.put("creditCondition", creditCondition);
        return mailMap;
    }

    @Override
    public Map<String, Object> selectMailInfo(Map<String, Object> map) {
        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("DealerNameEN", "basicInformation.getDealerNameEN()");
        mailMap.put("DealerNameCN", "basicInformation.getDealerNameCN()");
        mailMap.put("sector", "basicInformation.getSector()");
        mailMap.put("current_year", "");
        mailMap.put("limit", "approvedLimitAndCondition.getLimittype()");
        mailMap.put("deposit", "approvedLimitAndCondition.getCurrentsecurityratio()");
        mailMap.put("guarantee_structure", "");
        mailMap.put("approvedLimitAndCondition", "approvedLimitAndCondition");
        mailMap.put("creditCondition", "creditCondition");
        return mailMap;
    }

    @Override
    public Map<String, Object> selectMailInfoByInstanceId(String instanceId) {

        String sector = "byd";
        String dealerNameEN = "Dealer Name EN";
        String dealerNameCN = "Dealer Name CN";
        String currentYear = "byd";
        String limit = "5";
        String deposit = "10";
        String guaranteeStructure = "guarantee structure";

        StringBuilder table = new StringBuilder("<html ><body>");
        table.append("<table border=\"1\">\n");
        table.append("<tr>\n");
        table.append("<td rowspan=\"2\">Dealer Name</td>\n");
        table.append(" <td rowspan=\"2\">Brand</td>\n");
        table.append("<td rowspan=\"2\">Limit Type</td>\n");
        table.append("<td rowspan=\"2\">Active Limit</td>\n");
        table.append("<td rowspan=\"2\">OS</td>\n");
        table.append("<td colspan=\"2\">Current</td>\n");
        table.append("<td colspan=\"2\">Proposed</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Approved Limit</td>\n");
        table.append("<td>Deposit%</td>\n");
        table.append("<td>Approved Limit</td>\n");
        table.append("<td>Deposit%</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"5\">Ningbo\n");
        table.append("<br>\n");
        table.append("Zhongxinbole\n");
        table.append("<br>\n");
        table.append("Auto\n");
        table.append("<br>\n");
        table.append("Sales&Service\n");
        table.append("<br>\n");
        table.append("Co., Ltd.</td>\n");
        table.append(" <td rowspan=\"2\">CKD</td>\n");
        table.append("<td>Normal</td>\n");
        table.append("<td>3,180,000</td>\n");
        table.append("<td>2,002,148</td>\n");
        table.append("<td>3,500,000</td>\n");
        table.append("<td rowspan=\"5\">15%</td>\n");
        table.append("<td>3,500,000</td>\n");
        table.append("<td rowspan=\"5\">15%</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Demo</td>\n");
        table.append("<td>150,000</td>\n");
        table.append("<td>145,703</td>\n");
        table.append("<td>1,000,000</td>\n");
        table.append("<td>1,000,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"3\">BUX</td>\n");
        table.append("<td >Normal</td>\n");
        table.append("<td >7,200,000</td>\n");
        table.append("<td >4,768,000</td>\n");
        table.append("<td >7,200,000</td>\n");
        table.append("<td>7,200,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td rowspan=\"2\">Demo</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("<td rowspan=\"2\">693,645</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("<td rowspan=\"2\">800,000</td>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("</tr>\n");

        table.append("<tr>\n");
        table.append("<td>Total</td>\n");
        table.append("<td></td>\n");
        table.append("<td></td>\n");
        table.append("<td>11,330,000</td>\n");
        table.append("<td>7,609,495</td>\n");
        table.append("<td>12,500,000</td>\n");
        table.append("<td></td>\n");
        table.append("<td>12,500,000</td>\n");
        table.append("<td></td>\n");
        table.append("</tr>\n");
        table.append("</table></body></html>\n");
        String content = "Dear Committee,\n" +
                "\n" +
                "This is to seek your approval of " + sector + " dealer – " + dealerNameEN + " " + dealerNameCN + " " + currentYear + " annual review.\n" +
                "\n" +
                "As proposed by dealer and Sales team, we suggest to\n" +
                //"[根据workflow Approved Limit and Condition]\n" +
                "1)Maintain CKD limit of 4.5M and BUX limit of 8M;" + "[" + limit + "]\n" +
                "2)Maintain cash deposit ratio at 15%;[" + deposit + "%]\n" +
                "3)Maintain guarantee structure – Ningbo Bonded Port Fengzhe Investment and" +
                " Management Co., Ltd. (宁波梅山保税港区丰哲投资管理有限公司), Ye Wenjie (叶文杰) " +
                "and Wang Wei (王伟) [" + guaranteeStructure + "]\n" +
                "4)Special Approval:\n" +
                "\n" +
                "Basic information\n" +
                "[取workflow Approved Limit and Condition]\n" +
                table +
                "\n" +
                "Credit Comments:\n" +
                "[取workflow credit comments]\n" +
                "\n" +
                "Please find detailed information and analysis in annual review report.";


        Map<String, Object> mailMap = new HashMap<>();
        mailMap.put("to", "1404027183@qq.com");
        mailMap.put("title", "测试邮件发送内容格式225");
        mailMap.put("content", content);

        return mailMap;
    }

    @Override
    public int updateMain(Map<String, Object> map) {
        String parantInstanceId = "";
        Task task = taskService.createTaskQuery()
                .taskId(map.get("id")
                        .toString())
                .singleResult();
        List<HistoricDetail> historicDetails = SpringUtils.getBean(HistoryService.class)
                .createHistoricDetailQuery()
                .variableUpdates()
                .processInstanceId(task.getProcessInstanceId())
                .list();
        for (HistoricDetail historicDetail : historicDetails) {
            HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
            if ("parentId".equals(historicVariableUpdate.getVariableName())) {
                parantInstanceId = (String) historicVariableUpdate.getValue();
            }
        }

        DealerNegativeInformationCheck dealerNegativeInformationCheck = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck.setId(parantInstanceId);
        DealerNegativeInformationCheck flag = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parantInstanceId);

        Object ishavenagetiveinformation = map.get("ishavenagetiveinformation");
        Object nagetiveinformationtext = map.get("nagetiveinformationtext");
        Object dmvisitandsubmit = map.get("dmvisitandsubmit");
        Object visitandsubmittext = map.get("visitandsubmittext");
        Object ishavestockauditissue = map.get("ishavestockauditissue");
        Object stockauditissuetext = map.get("stockauditissuetext");
        Object isgetcarsto4sshop = map.get("isgetcarsto4sshop");
        Object getcarsto4sshoptext = map.get("getcarsto4sshoptext");
        Object ishaveillegalparkingin3month = map.get("ishaveillegalparkingin3month");
        Object illegalparkingtext = map.get("illegalparkingtext");
        Object isabnormalsituation = map.get("isabnormalsituation");
        Object abnormalsituationtext = map.get("abnormalsituationtext");
        Object ishaveloanextension = map.get("ishaveloanextension");
        Object loanextensiontext = map.get("loanextensiontext");
        Object ispaidup = map.get("ispaidup");
        Object paiduptext = map.get("paiduptext");

        DealerNegativeInformationCheck dealerNegativeInformationCheckI = JSON.parseObject(JSON.toJSONString(map), DealerNegativeInformationCheck.class);
        dealerNegativeInformationCheckI.setInstanceId(String.valueOf(parantInstanceId));
        dealerNegativeInformationCheckI.setId(String.valueOf(parantInstanceId));
        if (null != ishavenagetiveinformation || (null != nagetiveinformationtext && !"".equals(nagetiveinformationtext)) || null != dmvisitandsubmit || (null != visitandsubmittext && !"".equals(visitandsubmittext))) {
            dealerNegativeInformationCheckI.setIsStartDM(false);
        }
        if (null != ishavestockauditissue || (null != stockauditissuetext && !"".equals(stockauditissuetext)) || null != isgetcarsto4sshop || (null != getcarsto4sshoptext && !"".equals(getcarsto4sshoptext)) || null != ishaveillegalparkingin3month || (null != illegalparkingtext && !"".equals(illegalparkingtext)) || null != isabnormalsituation || (null != abnormalsituationtext && !"".equals(abnormalsituationtext)) || null != ishaveloanextension || (null != loanextensiontext && !"".equals(loanextensiontext)) || null != ispaidup || (null != paiduptext && !"".equals(paiduptext))) {
            dealerNegativeInformationCheckI.setIsStartPLM(false);
        }
        if (null == flag) {
            dealerNegativeInformationCheckService.insertDealerNegativeInformationCheck(dealerNegativeInformationCheckI);
        } else {
            dealerNegativeInformationCheckService.updateDealerNegativeInformationCheck(dealerNegativeInformationCheckI);
        }
        return 1;
    }

    @Override
    public AjaxResult deleteMain(String id) {
        if(StringUtils.isNotEmpty(id)){
          return AjaxResult.success(dealerNegativeInformationCheckService.deleteDealerNegativeInformationCheckById(id));
        }
        return  AjaxResult.error(0,"主键ID缺失，删除失败");
    }

    @Override
    public DealerNegativeInformationCheck getMain(String taskId) {
        String parantInstanceId = "";
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();
        List<HistoricDetail> historicDetails = SpringUtils.getBean(HistoryService.class)
                .createHistoricDetailQuery()
                .variableUpdates()
                .processInstanceId(task.getProcessInstanceId())
                .list();
        for (HistoricDetail historicDetail : historicDetails) {
            HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
            if ("parentId".equals(historicVariableUpdate.getVariableName())) {
                parantInstanceId = (String) historicVariableUpdate.getValue();
            }
        }
        DealerNegativeInformationCheck dealerNegativeInformationCheck = new DealerNegativeInformationCheck();
        dealerNegativeInformationCheck.setId(parantInstanceId);
        dealerNegativeInformationCheck = dealerNegativeInformationCheckService.selectDealerNegativeInformationCheckById(parantInstanceId);
        return dealerNegativeInformationCheck;
    }

    @Override
    public List<AnnualReviewyVO> selectAnnualReviewyVOList(AnnualReviewy annualReviewy) {
        String instanceId = annualReviewy.getInstanceId();
        List<AnnualReviewyVO> list = new ArrayList<>();
        AnnualReviewyVO annualReviewyVO = null;
        List<SalesPerformanceAndTarget> salesPerformanceAndTarget = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetByInstanceId(instanceId);
        List<LimitCalculationForCommericalNeeds> limitCalculationForCommericalNeeds = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsByInstanceId(instanceId);
        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketing = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingByInstanceId(instanceId);
        List<OtherFinancingResource> otherFinancingResource = otherFinancingResourceMapper.selectOtherFinancingResourceByInstanceId(instanceId);
        List<Securities> securities = securitiesMapper.selectSecuritiesByInstanceId(instanceId);
        Notes notes = notesMapper.selectNotesByInstanceId(instanceId);

        if (salesPerformanceAndTarget != null && salesPerformanceAndTarget.size() > 0) {
            annualReviewyVO = new AnnualReviewyVO();
            annualReviewyVO.setSalesPerformanceAndTarget(salesPerformanceAndTarget);
        }

        if (limitCalculationForCommericalNeeds != null && limitCalculationForCommericalNeeds.size() > 0) {
            for (LimitCalculationForCommericalNeeds limitCalculationForCommericalNeed : limitCalculationForCommericalNeeds) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeed);
            }
        }

        if (proposalByCommericalAndMarketing != null && proposalByCommericalAndMarketing.size() > 0) {
            for (ProposalByCommericalAndMarketing byCommericalAndMarketing : proposalByCommericalAndMarketing) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setProposalByCommericalAndMarketing(byCommericalAndMarketing);
            }
        }

        if (otherFinancingResource != null && otherFinancingResource.size() > 0) {
            for (OtherFinancingResource financingResource : otherFinancingResource) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setOtherFinancingResource(financingResource);
            }
        }

        if (securities != null && securities.size() > 0) {
            for (Securities security : securities) {
                annualReviewyVO = new AnnualReviewyVO();
                annualReviewyVO.setSecurities(security);
            }
        }

        if (notes != null) {
            annualReviewyVO.setNotes(notes);
        }
        list.add(annualReviewyVO);
        return list;
    }

    //根据条件搜索
    @Override
    @DataSource(value = DataSourceType.MASTER)
    public Page<ActTaskDTO> selectProcessDefinitionSearchList(SearchVo searchVo, PageDomain pageDomain) {
        Page<ActTaskDTO> list = new Page<ActTaskDTO>();
        Page<ActTaskDTO> list2 = new Page<ActTaskDTO>();
        String authenticatedUserId = this.securityManager.getAuthenticatedUserId();
        if (authenticatedUserId != null && !authenticatedUserId.isEmpty()) {
            List<String> userGroups = this.userGroupManager.getUserGroups(authenticatedUserId);
            org.activiti.api.runtime.shared.query.Page<org.activiti.api.task.model.Task> pageTasks = null;
            pageTasks = this.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()), TaskPayloadBuilder.tasks().withAssignee(authenticatedUserId).withGroups(userGroups).build(), searchVo);
            if(pageTasks.getTotalItems()<(pageDomain.getPageNum() - 1) * pageDomain.getPageSize()){
                pageDomain.setPageNum(1);
                pageTasks = this.tasks(Pageable.of((pageDomain.getPageNum() - 1) * pageDomain.getPageSize(), pageDomain.getPageSize()), TaskPayloadBuilder.tasks().withAssignee(authenticatedUserId).withGroups(userGroups).build(), searchVo);
            }
            List<org.activiti.api.task.model.Task> tasks = pageTasks.getContent();
            int totalItems = pageTasks.getTotalItems();
            list.setTotal(totalItems);
            list2.setTotal(totalItems);
            if (totalItems != 0) {
                Set<String> processInstanceIdIds = tasks.parallelStream().map(t -> t.getProcessInstanceId()).collect(Collectors.toSet());
                // List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyByInstanceIds(new ArrayList<>(processInstanceIdIds));
                List<org.activiti.engine.runtime.ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().processInstanceIds(processInstanceIdIds).list();
                Set<String> businessKeys = processInstanceList.parallelStream().map(t -> t.getBusinessKey()).collect(Collectors.toSet());
                List<BasicInformation> basicInformations = basicInformationMapper.selectDealerGroupByByInstanceIds(businessKeys);
                List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyListByInstanceIds(businessKeys);
                Set<String> userIds = processInstanceList.parallelStream().map(t -> t.getStartUserId()).collect(Collectors.toSet());
                List<Map> maps = userMapper.selectUsersByIds(userIds);
                List<ActTaskDTO> actTaskDTOS = tasks.stream().map(t -> {
                    ActTaskDTO actTaskDTO = new ActTaskDTO(t, processInstanceList.parallelStream().filter(pi ->
                            t.getProcessInstanceId().equals(pi.getId())).findAny().get());
                    String startUserId = actTaskDTO.getStartUserId();
                    for (Map map : maps) {
                        if (map.get("user_id").toString().equals(startUserId)) {
                            ActWorkflowFormData actWorkflowFormDataByBusinessKey = actWorkflowFormDataService.getActWorkflowFormDataByBusinessKey(actTaskDTO.getBusinessKey());
                            actTaskDTO.setAssignee(map.get("nick_name").toString());
                            if(ObjectUtil.isNotEmpty(actWorkflowFormDataByBusinessKey)){
                                actTaskDTO.setLastUserName(actWorkflowFormDataByBusinessKey.getCreateBy());
                            }
                        }
                    }
                    StringBuffer dealerName = new StringBuffer();
                    StringBuffer sector = new StringBuffer();
                    Set<String> setString =new HashSet<>();
                    for (BasicInformation basicInformation : basicInformations) {
                        if (basicInformation.getInstanceId().equals(actTaskDTO.getBusinessKey())) {

                            if (null != basicInformation.getGroupNameEN() && !"".equals(basicInformation.getGroupNameEN())) {
                                actTaskDTO.setGroupName(basicInformation.getGroupNameEN());
                            }
                            if(null != basicInformation.getDealerNameCN() && !"".equals(basicInformation.getDealerNameCN())){
                                dealerName.append(basicInformation.getDealerNameCN()).append(",");
                            }
                            if(null != basicInformation.getSector() && !"".equals(basicInformation.getSector())){
                                sector.append(basicInformation.getSector()).append(",");

                            }
                            HDealerDm hDealerDm = hDealerDmMapper.selectHDealerDmByDealerName(basicInformation.getDealerNameCN());
                            if(hDealerDm!=null && StringUtils.isNotEmpty(hDealerDm.getUwName())){
                                setString.add(hDealerDm.getUwName());
                            }
                        }
                    }
                    if(setString.size()>0){
                        String join = StringUtils.join(setString, ",");
                        actTaskDTO.setUw(join);
                    }
                    for (AnnualReviewy annualReviewy : annualReviewies) {
                        if (annualReviewy.getInstanceId().equals(actTaskDTO.getBusinessKey())) {
                            actTaskDTO.setCreatedDate(annualReviewy.getUwDate());
                            if(annualReviewy.getInstanceId().contains("WLS") && StringUtils.isNotEmpty(annualReviewy.getUwApprovalName())){
                                actTaskDTO.setUw(annualReviewy.getUwApprovalName());
                            }
                        }

                    }
                    if(dealerName!=null && dealerName.length()>1){
                        dealerName.deleteCharAt(dealerName.length() - 1);
                        actTaskDTO.setDealerName(dealerName.toString());
                    }

                    if(sector!=null && sector.length()>1){
                        sector.deleteCharAt(sector.length() - 1);
                        actTaskDTO.setSector(sector.toString());
                    }
                    return actTaskDTO;
                })
                        .collect(Collectors.toList());

                list.addAll(actTaskDTOS);

            }
            if ("dealerName".equals(searchVo.getOrderByColumn())) {
                if ("asc".equals(searchVo.getOrder())) {
                    List<ActTaskDTO> result = list.getResult();
                    Collections.sort(result, new Comparator<ActTaskDTO>() {
                        @Override
                        public int compare(ActTaskDTO o1, ActTaskDTO o2) {
                            if(o1.getDealerName()!=null && o2.getDealerName()!=null){
                                return o2.getDealerName().substring(0).compareTo(o1.getDealerName().substring(0));
                            }
                            return "".compareTo("");
                        }

                        @Override
                        public boolean equals(Object obj) {
                            return false;
                        }
                    });
                    list2.addAll(result);
                    return list2;
                } else {
                    List<ActTaskDTO> result = list.getResult();
                    Collections.sort(result, new Comparator<ActTaskDTO>() {
                        @Override
                        public int compare(ActTaskDTO o1, ActTaskDTO o2) {
                            if(o1.getDealerName()!=null && o2.getDealerName()!=null){
                                return o1.getDealerName().substring(0).compareTo(o2.getDealerName().substring(0));
                            }
                            return "".compareTo("");
                        }

                        @Override
                        public boolean equals(Object obj) {
                            return false;
                        }
                    });
                    list2.addAll(result);
                    return list2;
                }
            }

            return list;
        } else {
            throw new IllegalStateException("You need an authenticated user to perform a task query");
        }

    }

    @Override
    public CustomPage indexData() {
        CustomPage customPage = new CustomPage();
        String username = SecurityUtils.getUsername();
        int yfqNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, null);
        int jxzNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, "0");
        int ywcNum = annualReviewyMapper.selectCountByCreatenameAndStatus(username, "1");
        customPage.setYfqNum(yfqNum);
        customPage.setJxzNum(jxzNum);
        customPage.setYwcNum(ywcNum);
        long ybcount = historyService.createHistoricTaskInstanceQuery().taskAssignee(username).finished().count();
        customPage.setYclNum(ybcount);
        return customPage;
    }

    public org.activiti.api.runtime.shared.query.Page<org.activiti.api.task.model.Task> tasks(Pageable pageable, GetTasksPayload getTasksPayload, SearchVo searchVo) {
        TaskQuery taskQuery = this.taskService.createTaskQuery();
        if (getTasksPayload == null) {
            getTasksPayload = TaskPayloadBuilder.tasks().build();
        }

        String authenticatedUserId = this.securityManager.getAuthenticatedUserId();
        if (authenticatedUserId != null && !authenticatedUserId.isEmpty()) {
            List<String> tasks = this.userGroupManager.getUserGroups(authenticatedUserId);
            getTasksPayload.setAssigneeId(authenticatedUserId);
            getTasksPayload.setGroups(tasks);
            taskQuery = (TaskQuery) ((TaskQuery) ((TaskQuery) taskQuery.or()).taskCandidateOrAssigned(getTasksPayload.getAssigneeId(), getTasksPayload.getGroups()).taskOwner(authenticatedUserId)).endOr();
            if (getTasksPayload.getProcessInstanceId() != null) {
                taskQuery = (TaskQuery) taskQuery.processInstanceId(getTasksPayload.getProcessInstanceId());
            }

            if (getTasksPayload.getParentTaskId() != null) {
                taskQuery = (TaskQuery) taskQuery.taskParentTaskId(getTasksPayload.getParentTaskId());
            }
            boolean hasName = false;
            boolean hasTime = false;
            Set<String>  uws = new HashSet<>();
            List<String> uwsList = null;
            BasicInformation basicInformation = new BasicInformation();
            if (StringUtils.isNotBlank(searchVo.getGroupNameCN())) {
                basicInformation.setGroupNameEN(searchVo.getGroupNameCN());
                hasName = true;
            }
            if (StringUtils.isNotBlank(searchVo.getDealerNameCN())) {
                basicInformation.setDealerNameCN(searchVo.getDealerNameCN());
                hasName = true;
            }
            if (searchVo.getStartDate() != null && searchVo.getEndDate() != null) {
                hasTime = true;
            }
            if (StringUtils.isNotEmpty(searchVo.getUw())) {
                HDealerDm hDealerDm = new HDealerDm();
                hDealerDm.setUwName(searchVo.getUw());
                List<HDealerDm> hDealerDms = hDealerDmMapper.selectHDealerDmListGroupByUW(hDealerDm);
                if(hDealerDms!=null && hDealerDms.size()>0){
                    for (HDealerDm dealerDm : hDealerDms) {
                        BasicInformation basicInformationTemp = new BasicInformation();
                        basicInformationTemp.setDealerNameCN(dealerDm.getDealerName());
                        List<BasicInformation> basicInformationsTemp = basicInformationMapper.deleteBasicInformationAnnualDealernameList(dealerDm.getDealerName());
                        if(basicInformationsTemp!=null&&basicInformationsTemp.size()>0 ){
                            for (BasicInformation information : basicInformationsTemp) {
                                if(information!=null && information.getInstanceId()!=null){
                                    uws.add(information.getInstanceId());
                                }

                            }

                        }
                    }
                }
                if(uws!=null && uws.size()>0){
                    uwsList = new ArrayList<>(uws);
                    System.out.println("uw的经销商");
                }else{
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }
            List<String> instanceIds = null;
            if (hasName && !hasTime) {
                List<BasicInformation> basicInformations = basicInformationMapper.selectBasicInformationList(basicInformation);
                instanceIds = basicInformations.parallelStream().map(t -> {
                    return t.getInstanceId();
                }).collect(Collectors.toList());
                //判断有没有uw
                System.out.println("选择了经销商List:"+instanceIds.toString());
                if(uwsList!=null && uwsList.size()>0){
                    instanceIds.retainAll(uwsList);
                    System.out.println("选择了uw去重后List:" + instanceIds.toString());
                }
                List<String> processInstanceIdIds = new ArrayList<>();
                if (null != instanceIds && instanceIds.size() > 0) {
                    for (String instanceId : instanceIds) {
                        org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
                        if(null!=processInstance){
                            processInstanceIdIds.add(processInstance.getProcessInstanceId());
                        }
                    }
                    if (null != processInstanceIdIds && 0 != processInstanceIdIds.size()) {
                        taskQuery.processInstanceIdIn(processInstanceIdIds);
                    } else {
                        return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                    }
                } else {
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }else if (!hasName && hasTime){
                AnnualReviewy annualReviewy = new AnnualReviewy();
                annualReviewy.setStartDate(searchVo.getStartDate());
                annualReviewy.setEndDate(searchVo.getEndDate());
                List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyListByDate(annualReviewy);
                instanceIds = annualReviewies.parallelStream().map(t -> {
                    return t.getInstanceId();
                }).collect(Collectors.toList());

                //判断有没有uw
                System.out.println("选择了UW Date List:"+instanceIds.toString());
                if(uwsList!=null && uwsList.size()>0){
                    instanceIds.retainAll(uwsList);
                    System.out.println("选择了uw去重后List:" + instanceIds.toString());
                }
                List<String> processInstanceIdIds = new ArrayList<>();
                if (null != instanceIds && instanceIds.size() > 0) {
                    for (String instanceId : instanceIds) {
                        org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
                        if(null!=processInstance){
                            processInstanceIdIds.add(processInstance.getProcessInstanceId());
                        }
                    }
                    if (null != processInstanceIdIds && 0 != processInstanceIdIds.size()) {
                        taskQuery.processInstanceIdIn(processInstanceIdIds);
                    } else {
                        return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                    }
                } else {
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }else if (hasName && hasTime){
                List<BasicInformation> basicInformations = basicInformationMapper.selectBasicInformationList(basicInformation);
                List<String> instanceIdsByName = basicInformations.parallelStream().map(t -> {
                    return t.getInstanceId();
                }).collect(Collectors.toList());
                AnnualReviewy annualReviewy = new AnnualReviewy();
                annualReviewy.setStartDate(searchVo.getStartDate());
                annualReviewy.setEndDate(searchVo.getEndDate());
                List<AnnualReviewy> annualReviewies = annualReviewyMapper.selectAnnualReviewyListByDate(annualReviewy);
                List<String> instanceIdsByDate = annualReviewies.parallelStream().map(t -> {
                    return t.getInstanceId();
                }).collect(Collectors.toList());
                if(instanceIdsByName.size()>0 && instanceIdsByDate.size()>0){
                    List<String> processInstanceIdIds = new ArrayList<>();
                    instanceIdsByName.retainAll(instanceIdsByDate);
                    //判断有没有uw
                    System.out.println("选择了UW Date和经销商 List:"+instanceIdsByName.toString());
                    if(uwsList!=null && uwsList.size()>0){
                        instanceIdsByName.retainAll(uwsList);
                        System.out.println("选择了uw去重后List:" + instanceIds.toString());
                    }
                    if(instanceIdsByName.size()>0){
                        for (String instanceId : instanceIdsByName) {
                            org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
                            if(null!=processInstance){
                                processInstanceIdIds.add(processInstance.getProcessInstanceId());
                            }
                        }
                    }
                    if (null != processInstanceIdIds && 0 != processInstanceIdIds.size()) {
                        taskQuery.processInstanceIdIn(processInstanceIdIds);
                    } else {
                        return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                    }
                }else{
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }else if(uwsList!=null && uwsList.size()>0){
                List<String> processInstanceIdIds = new ArrayList<>();
                for (String instanceId : uwsList) {
                    //try{
                    org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
                    if(null!=processInstance){
                        processInstanceIdIds.add(processInstance.getProcessInstanceId());
                    }
                   // }catch (Exception e){
                    //    continue;
                   // }
                }
                if (null != processInstanceIdIds && 0 != processInstanceIdIds.size()) {
                    taskQuery.processInstanceIdIn(processInstanceIdIds);
                } else {
                    return new PageImpl(new ArrayList<org.activiti.api.task.model.Task>(), 0);
                }
            }

            if (StringUtils.isNotBlank(searchVo.getBusinessKey())) {
                taskQuery.processInstanceBusinessKey(searchVo.getBusinessKey());
            }
            if (StringUtils.isNotBlank(searchVo.getName())) {
                taskQuery.taskName(searchVo.getName());
            }
            if (StringUtils.isNotBlank(searchVo.getType())) {
                taskQuery.processDefinitionKey(searchVo.getType());
            }
/*            if (searchVo.getStartDate() != null) {
                taskQuery.taskCreatedAfter(searchVo.getStartDate());
            }
            if (searchVo.getEndDate() != null) {
                taskQuery.taskCreatedBefore(searchVo.getEndDate());
            }*/
            if ("createdDate".equals(searchVo.getOrderByColumn())) {
                if ("asc".equals(searchVo.getOrder())) {
                    taskQuery.orderByTaskCreateTime().asc();
                } else {
                    taskQuery.orderByTaskCreateTime().desc();
                }
            } else if ("name".equals(searchVo.getOrderByColumn())){
                if ("asc".equals(searchVo.getOrder())) {
                    taskQuery.orderByTaskName().asc();
                    taskQuery.orderByTaskCreateTime().desc();
                } else {
                    taskQuery.orderByTaskName().desc();
                    taskQuery.orderByTaskCreateTime().desc();
                }
            }else{
                taskQuery.orderByTaskCreateTime().desc();
            }

            List<org.activiti.api.task.model.Task> tasksRs = this.taskConverter.from(taskQuery.listPage(pageable.getStartIndex(), pageable.getMaxItems()));
            return new PageImpl(tasksRs, Math.toIntExact(taskQuery.count()));
        } else {
            throw new IllegalStateException("You need an authenticated user to perform a task query");
        }
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public List<Map<String, Object>> listWprvo(List<String> map) {
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ArrayList<Map<String, Object>> listss = new ArrayList<>();
//        ArrayList<Map<String, Object>> list = new ArrayList<>();
//        for(String maps : map){
//            List<WholesalePerformanceRecentVO> wholesalePerformanceRecentVOS = wholesalePerformanceRecentMapper.selectBalanceInformationList(maps);
//            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
//            objectObjectHashMap.put("dealerName",maps);
//            objectObjectHashMap.put("children",wholesalePerformanceRecentVOS);
//            list.add(objectObjectHashMap);
//        }
        List<String> stringList = new ArrayList<>();


        List<String> resultListnew = new ArrayList<String>();
        String lastMonthByNum1 = DateUtils.getLastMonthByNum(-1);
        String lastMonthByNum2 = DateUtils.getLastMonthByNum(-2);
        String lastMonthByNum3 = DateUtils.getLastMonthByNum(-3);
        resultListnew.add(lastMonthByNum1);
        resultListnew.add(lastMonthByNum2);
        resultListnew.add(lastMonthByNum3);
        Collections.reverse(resultListnew);

        stringList.add("Dealer");
        stringList.add("Sector");

        for (String res : resultListnew) {
            stringList.add(res);
        }
        //转成不带“-”
        ArrayList<String> objects = new ArrayList<>();
        for (String res : resultListnew) {
            objects.add(res);
        }
        HashMap<String, Object> map1 = new HashMap<>();
        for (String maps : map) {
            WholesalePerformanceRecentVO wholesalePerformanceRecentVO = new WholesalePerformanceRecentVO();
            wholesalePerformanceRecentVO.setDealerName(maps);
            wholesalePerformanceRecentVO.setTime(StringUtils.strip(objects.toString(), "[]"));
            ArrayList<Map<String, Object>> ob = new ArrayList<>();

            List<Map<String, Object>> wholesalePerformanceRecentVOS = wholesalePerformanceRecentMapper.selectBalanceInformationList(wholesalePerformanceRecentVO);
            ArrayList<Map<String, Object>> objects1 = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : wholesalePerformanceRecentVOS) {
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();

                objectObjectHashMap.put(stringList.get(0), stringObjectMap.get("DEALER_NAME"));
                objectObjectHashMap.put(stringList.get(1), stringObjectMap.get("BRAND"));

                if (StringUtils.isNotNull(stringObjectMap.get(resultListnew.get(0)))) {
                    objectObjectHashMap.put(resultListnew.get(0), stringObjectMap.get(resultListnew.get(0)));
                } else {
                    objectObjectHashMap.put(resultListnew.get(0), "");
                }
                if (StringUtils.isNotNull(stringObjectMap.get(resultListnew.get(1)))) {
                    objectObjectHashMap.put(resultListnew.get(1), stringObjectMap.get(resultListnew.get(1)));
                } else {
                    objectObjectHashMap.put(resultListnew.get(1), "");
                }
                if (StringUtils.isNotNull(stringObjectMap.get(resultListnew.get(2)))) {
                    objectObjectHashMap.put(resultListnew.get(2), stringObjectMap.get(resultListnew.get(2)));
                } else {
                    objectObjectHashMap.put(resultListnew.get(2), "");
                }

                objects1.add(objectObjectHashMap);

            }

            list.addAll(objects1);
        }
        //TODO 待定格式不对
        map1.put("title", stringList);
        map1.put("row", list);
        listss.add(map1);
        return listss;
    }

    @Override
//    @DataSource(value = DataSourceType.SLAVE)
    public List<Map<String, Object>> listWprvoApproval(Map<String, Object> map) {
        String instanceId = (String) map.get("instanceId");
        List<String> dealerName = (List<String>) map.get("dealerName");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        ArrayList<Map<String, Object>> listss = new ArrayList<>();
        List<String> stringList = new ArrayList<>();

        List<String> listthead = null;
        HashMap<String, Object> map1 = new HashMap<>();
        for (String maps : dealerName) {
            WholesalePerformanceRecentThreeMonths wholesalePerformanceRecentVO = new WholesalePerformanceRecentThreeMonths();
            wholesalePerformanceRecentVO.setDEALER(maps);
            wholesalePerformanceRecentVO.setInstanceId(instanceId);
            wholesalePerformanceRecentVO.setType("OS");
            ArrayList<Map<String, Object>> ob = new ArrayList<>();

            List<WholesalePerformanceRecentThreeMonths> wholesalePerformanceRecentVOS = wholesalePerformanceRecentThreeMonthsMapper.selectWholesalePerformanceRecentThreeMonthsList(wholesalePerformanceRecentVO);
            ArrayList<Map<String, Object>> objects1 = new ArrayList<>();
            for (WholesalePerformanceRecentThreeMonths stringObjectMap : wholesalePerformanceRecentVOS) {
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                String thead = stringObjectMap.getThead();
                listthead = Arrays.asList(thead.split(","));
                objectObjectHashMap.put(listthead.get(0), stringObjectMap.getDEALER());
                objectObjectHashMap.put(listthead.get(1), stringObjectMap.getBRAND());

                if (StringUtils.isNotNull(stringObjectMap.getLastLastYearMonth())) {
                    objectObjectHashMap.put(listthead.get(2), stringObjectMap.getLastLastYearMonth());
                } else {
                    objectObjectHashMap.put(listthead.get(2), "");
                }
                if (StringUtils.isNotNull(stringObjectMap.getLastYearMonth())) {
                    objectObjectHashMap.put(listthead.get(3), stringObjectMap.getLastYearMonth());
                } else {
                    objectObjectHashMap.put(listthead.get(3), "");
                }
                if (StringUtils.isNotNull(stringObjectMap.getCurrentYearMonth())) {
                    objectObjectHashMap.put(listthead.get(4), stringObjectMap.getCurrentYearMonth());
                } else {
                    objectObjectHashMap.put(listthead.get(4), "");
                }

                objects1.add(objectObjectHashMap);

            }
            list.addAll(objects1);
        }
        map1.put("title", listthead);
        map1.put("row", list);
        listss.add(map1);
        return listss;
    }

    @Override
    @DataSource(value = DataSourceType.SLAVE)
    public List<Map<String, Object>> listspat(List<String> map) {

        ArrayList<Map<String, Object>> list = new ArrayList<>();
        Date DateTemp = null;
        String flagDate = "2024-02-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
          DateTemp = sdf.parse(flagDate);
        }catch (Exception e){

        }

        for (String maps : map) {
            List<String> resultList = new ArrayList<String>();
            if(new Date().getTime()>DateTemp.getTime()){
                List<String> stringList = new ArrayList<>();
                Calendar cal = Calendar.getInstance();
                //近三个月带“-”
                cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + 1); //要先+1,才能把本月的算进去
                for (int i = 0; i < 2; i++) {
                    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) - 1); //逐次往前推1个月
                    resultList.add(String.valueOf(cal.get(Calendar.YEAR))
                    );
                }
                Collections.reverse(resultList);
            }else{
                resultList.add("2022");
                resultList.add("2023");
            }

            //表格头
            ArrayList<String> objects = new ArrayList<>();
            ArrayList<Map<String, Object>> objects1 = new ArrayList<>();
            HashMap<String, Object> objectObjectHashMap1 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap2 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap3 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap4 = new HashMap<>();

            objects.add("Item");
            objects.add("Sector");
            objectObjectHashMap1.put("first", objects);
            objectObjectHashMap2.put("title", "YR" + resultList.get(0));
            objectObjectHashMap2.put("children", "Actual");
            objects1.add(objectObjectHashMap2);
            objectObjectHashMap3.put("title", "YTD" + resultList.get(1));
            objectObjectHashMap3.put("children", "Actual");
            objects1.add(objectObjectHashMap3);
//            objectObjectHashMap4.put("title","YR"+resultList.get(1));
//            objectObjectHashMap4.put("children","Target");
//            objects1.add(objectObjectHashMap4);
            objectObjectHashMap1.put("second", objects1);

            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
            ArrayList<Map<String, Object>> lists = new ArrayList<>();
            ArrayList<Map<String, Object>> lists2 = new ArrayList<>();
            ArrayList<String> strings1 = new ArrayList<>();
            ArrayList<String> strings2 = new ArrayList<>();
            int a = 1;
            SalesPerformanceAndTargetOrcaleVO svo = new SalesPerformanceAndTargetOrcaleVO();
            svo.setDealerName(maps);
            svo.setTimehead(resultList.get(0));
            svo.setTimeend(resultList.get(1));
            svo.setTime(StringUtils.strip(resultList.toString(), "[]"));
            List<Map<String, Object>> salesPerformanceAndTargetOrcaleVOS = salesPerformanceAndTargetOrcaleMapper.selectSalesPerformanceAndTargetOrcaleListPs(svo);
            Map<String, Object> mapTemp = new TreeMap<String, Object>(
                    new Comparator<String>() {
                        public int compare(String obj1, String obj2) {
                            // 升序排序
                            return obj1.compareTo(obj2);
                        }
                    });
            for (Map<String, Object> spatPs : salesPerformanceAndTargetOrcaleVOS) {
                HashMap<String, Object> objectObjectHashMap5 = new HashMap<>();
                objectObjectHashMap5.put("dealerName", spatPs.get("DEALER_NAME"));
                objectObjectHashMap5.put("Sector", spatPs.get("BRAND"));
                strings1.add(spatPs.get("BRAND").toString().toUpperCase());
                objectObjectHashMap5.put("Item", spatPs.get("ITEM"));
                if (StringUtils.isNotNull(spatPs.get(resultList.get(0)))) {
                    objectObjectHashMap5.put("YR" + resultList.get(0), spatPs.get(resultList.get(0)));
                } else {
                    objectObjectHashMap5.put("YR" + resultList.get(0), "");
                }
                if (StringUtils.isNotNull(spatPs.get(resultList.get(1)))) {
                    objectObjectHashMap5.put("YTD" + resultList.get(1), spatPs.get(resultList.get(1)));
                } else {
                    objectObjectHashMap5.put("YTD" + resultList.get(1), "");
                }
//                objectObjectHashMap5.put("YR"+resultList.get(1),"");
                objectObjectHashMap5.put("currentYear", "");
                objectObjectHashMap5.put("id", a);
                mapTemp.put(spatPs.get("BRAND").toString(),objectObjectHashMap5);
                a++;
            }
            ArrayList<String> strings = new ArrayList<>();
            ArrayList<String> stringsTemp = new ArrayList<>();
            //判断查询回来的数据和经销商是否相等
            if(maps!= null ){
                DealerInformation dealerInformation = new DealerInformation();
                dealerInformation.setDealerName(maps);
                List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList(dealerInformation);
                for (DealerInformation information : dealerInformations) {
                    if(information.getMake()!= null){
                        if(information.getMake().toUpperCase().contains("NAVECO")){
                            strings.add("NAVECO");
                            stringsTemp.add("NAVECO");
                        }else{
                            strings.add(information.getMake().toUpperCase());
                            stringsTemp.add(information.getMake().toUpperCase());
                        }

                    }
                }
            }
            if(strings.size()>0){
                strings1.retainAll(strings);
                if(strings.size()>strings1.size()){
                    strings.removeAll(strings1);
                        if(strings.size()>0){
                            for (String s : strings) {
                                if(s!=null && !s.equals("SLB")) {
                                    HashMap<String, Object> objectObjectHashMap5 = new HashMap<>();
                                    objectObjectHashMap5.put("dealerName", maps);
                                    objectObjectHashMap5.put("Sector", s);
                                    objectObjectHashMap5.put("Item", "批售");
                                    objectObjectHashMap5.put("YR" + resultList.get(0), "");
                                    objectObjectHashMap5.put("YTD" + resultList.get(1), "");
                                    objectObjectHashMap5.put("currentYear", "");
                                    objectObjectHashMap5.put("id", a);
                                    mapTemp.put(s, objectObjectHashMap5);
                                    a++;
                                }
                            }
                        }
                }
            }

            //排序
            if(mapTemp != null ){
                Set<String> keySet = mapTemp.keySet();
                Iterator<String> iter = keySet.iterator();
                while (iter.hasNext()) {
                    String key = iter.next();
                    lists.add((Map<String, Object>)mapTemp.get(key));
                }
            }
            List<Map<String, Object>> wholesalePerformanceRecentVOS = salesPerformanceAndTargetOrcaleMapper.selectSalesPerformanceAndTargetOrcaleListLs(svo);
            Map<String, Object> mapTemp2 = new TreeMap<String, Object>(
                    new Comparator<String>() {
                        public int compare(String obj1, String obj2) {
                            // 升序排序
                            return obj1.compareTo(obj2);
                        }
                    });
            for (Map<String, Object> spat : wholesalePerformanceRecentVOS) {
                HashMap<String, Object> objectObjectHashMap5 = new HashMap<>();
                objectObjectHashMap5.put("dealerName", spat.get("DEALER_NAME"));
                objectObjectHashMap5.put("Sector", spat.get("BRAND"));
                strings2.add(spat.get("BRAND").toString().toUpperCase());
                objectObjectHashMap5.put("Item", spat.get("ITEM"));
                if (StringUtils.isNotNull(spat.get(resultList.get(0)))) {
                    objectObjectHashMap5.put("YR" + resultList.get(0), spat.get(resultList.get(0)));
                } else {
                    objectObjectHashMap5.put("YR" + resultList.get(0), "");
                }
                if (StringUtils.isNotNull(spat.get(resultList.get(1)))) {
                    objectObjectHashMap5.put("YTD" + resultList.get(1), spat.get(resultList.get(1)));
                } else {
                    objectObjectHashMap5.put("YTD" + resultList.get(1), "");
                }
//                objectObjectHashMap5.put("YR"+resultList.get(1),"");
                objectObjectHashMap5.put("currentYear", "");
                objectObjectHashMap5.put("id", a);
                mapTemp2.put(spat.get("BRAND").toString(),objectObjectHashMap5);
                a++;
            }
            if(stringsTemp.size()>0){
                strings2.retainAll(stringsTemp);
                if(stringsTemp.size()>strings2.size()){
                    stringsTemp.removeAll(strings2);
                    if(stringsTemp.size()>0){
                        for (String s : stringsTemp) {
                            if(s!=null && !s.equals("SLB")){
                                HashMap<String, Object> objectObjectHashMap5 = new HashMap<>();
                                objectObjectHashMap5.put("dealerName", maps);
                                objectObjectHashMap5.put("Sector", s);
                                objectObjectHashMap5.put("Item", "零售");
                                objectObjectHashMap5.put("YR" + resultList.get(0), "");
                                objectObjectHashMap5.put("YTD" + resultList.get(1), "");
                                objectObjectHashMap5.put("currentYear", "");
                                objectObjectHashMap5.put("id", a);
                                mapTemp2.put(s,objectObjectHashMap5);
                                a++;
                            }
                        }
                    }
                }
            }
            //排序
            if(mapTemp2 != null ){
                Set<String> keySet = mapTemp2.keySet();
                Iterator<String> iter = keySet.iterator();
                while (iter.hasNext()) {
                    String key = iter.next();
                    lists.add((Map<String, Object>)mapTemp2.get(key));
                }
            }
            for (Map<String, Object> stringObjectMap : lists) {
                if(stringObjectMap.get("Sector")!=null && !stringObjectMap.get("Sector").toString().equals("SLB")){
                    lists2.add(stringObjectMap);
                }
            }
            objectObjectHashMap.put("title", objectObjectHashMap1);
            objectObjectHashMap.put("dealerName", maps);
            objectObjectHashMap.put("children", lists);
            if(lists2!=null && lists2.size()>0){
                objectObjectHashMap.put("children", lists2);
            }
            list.add(objectObjectHashMap);
        }
        return list;
    }

    @Override
//    @DataSource(value = DataSourceType.SLAVE)
    public List<Map<String, Object>> listspatApproval(Map<String, Object> map) {
        String instanceId = (String) map.get("instanceId");
        List<String> dealerName = (List<String>) map.get("dealerName");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (String maps : dealerName) {
            SalesPerformanceAndTarget salesPerformanceAndTarget = new SalesPerformanceAndTarget();
            salesPerformanceAndTarget.setDealername(maps);
            salesPerformanceAndTarget.setInstanceId(instanceId);
            List<SalesPerformanceAndTarget> salesPerformanceAndTargets = salesPerformanceAndTargetMapper.selectSalesPerformanceAndTargetList(salesPerformanceAndTarget);

            List<String> stringList = new ArrayList<>();

            //表格头
            ArrayList<String> objects = new ArrayList<>();
            ArrayList<Map<String, Object>> objects1 = new ArrayList<>();
            HashMap<String, Object> objectObjectHashMap1 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap2 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap3 = new HashMap<>();
            HashMap<String, Object> objectObjectHashMap4 = new HashMap<>();

            if (salesPerformanceAndTargets.size() > 0) {
                String thead = salesPerformanceAndTargets.get(0).getThead();
                List<String> listthead = Arrays.asList(thead.split(","));

                objects.add("Item");
                objects.add("Sector");
                objectObjectHashMap1.put("first", objects);
                objectObjectHashMap2.put("title", listthead.get(0));
                objectObjectHashMap2.put("children", "Actual");
                objects1.add(objectObjectHashMap2);
                objectObjectHashMap3.put("title", listthead.get(1));
                objectObjectHashMap3.put("children", "Actual");
                objects1.add(objectObjectHashMap3);
//            objectObjectHashMap4.put("title",listthead.get(2));
//            objectObjectHashMap4.put("children","Target");
//            objects1.add(objectObjectHashMap4);
                objectObjectHashMap1.put("second", objects1);

                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                ArrayList<Map<String, Object>> lists = new ArrayList<>();
                int a = 1;

                for (SalesPerformanceAndTarget spat : salesPerformanceAndTargets) {
                    HashMap<String, Object> objectObjectHashMap5 = new HashMap<>();

                    objectObjectHashMap5.put("dealerName", spat.getDealername());
                    objectObjectHashMap5.put("Sector", spat.getSector());
                    objectObjectHashMap5.put("Item", spat.getItem());
                    if (StringUtils.isNotNull(spat.getActual2021())) {
                        objectObjectHashMap5.put(listthead.get(0), spat.getActual2021());
                    } else {
                        objectObjectHashMap5.put(listthead.get(0), "");
                    }
                    if (StringUtils.isNotNull(spat.getActualYTD2022())) {
                        objectObjectHashMap5.put(listthead.get(1), spat.getActualYTD2022());
                    } else {
                        objectObjectHashMap5.put(listthead.get(1), "");
                    }
                    if (StringUtils.isNotNull(spat.getTarget2022())){
                        objectObjectHashMap5.put("currentYear",spat.getTarget2022());
                    }else{
                        objectObjectHashMap5.put("currentYear","");
                    }
                    objectObjectHashMap5.put("id",spat.getId());

                    lists.add(objectObjectHashMap5);
                    a++;
                }

                objectObjectHashMap.put("title", objectObjectHashMap1);
                objectObjectHashMap.put("dealerName", maps);
                objectObjectHashMap.put("children", lists);
                list.add(objectObjectHashMap);
            }

        }
        return list;
    }

    @Override
    public List<Map<String, Object>> sectorinformationAndDealerinformation(List<String> map ,String instanceId) {
        //先通过dealername查dealerinformation对应得sector
//        String dealerName = (String)map.get("dealerName");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        int a = 1;
        for (String maps : map) {
            DealerInformation dealerInformation = new DealerInformation();
            dealerInformation.setDealerName(maps);
            if(StringUtils.isNotEmpty(maps)){
                List<DealerInformation> dealerInformations = dealerInformationService.selectDealerInformationList2(dealerInformation);
                Map<String, Object> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("dealerName", maps);
                Collections.sort(dealerInformations, new Comparator<DealerInformation>() {
                    @Override
                    public int compare(DealerInformation o1, DealerInformation o2) {
                        return o1.getMake().compareTo(o2.getMake());
                    }

                    @Override
                    public boolean equals(Object obj) {
                        return false;
                    }
                });
                ArrayList<SectorInformation> objects1 = new ArrayList<>();
                for (DealerInformation di : dealerInformations) {
                    SectorInformation sectorInformation = new SectorInformation();
                    sectorInformation.setSector(di.getMake());
                    //根据sector查对应得sectorinformation详细数据
                    List<SectorInformation> sectorInformations = sectorInformationMapper.selectSectorInformationList(sectorInformation);
                    if(StringUtils.isNotEmpty(instanceId)){
                        for (SectorInformation information : sectorInformations) {
                            LimitCalculationForCommericalNeeds dealerInformationTemp = new LimitCalculationForCommericalNeeds();
                            dealerInformationTemp.setDealername(maps);
                            dealerInformationTemp.setSector(information.getSector());
                            dealerInformationTemp.setModel(information.getModel());
                            dealerInformationTemp.setInstanceId(instanceId);
                            List<LimitCalculationForCommericalNeeds> dealerInformatiTemp = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsList(dealerInformationTemp);
                            for (LimitCalculationForCommericalNeeds limitCalculationForCommericalNeeds : dealerInformatiTemp) {
                                limitCalculationForCommericalNeeds.setAip(information.getAvgLoanAmt());
                                limitCalculationForCommericalNeeds.setAtd(information.getActualAvgDso().toString());
                                if(limitCalculationForCommericalNeeds.getEstimatedannualwholesaleunits() != null){
                                    Long avgLoanAmt = information.getAvgLoanAmt();
                                    String replace = limitCalculationForCommericalNeeds.getEstimatedannualwholesaleunits().replace(",", "");
                                    Long aLong = Long.valueOf(replace);
                                    Long actualAvgDso = information.getActualAvgDso();
                                    long l = avgLoanAmt * aLong * actualAvgDso / 360;
                                    limitCalculationForCommericalNeeds.setCreditlimitfornewvehicle(String.valueOf(l));
                                }
                                limitCalculationForCommericalNeedsMapper.updateLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeeds);
                            }
                         }
                    }
                    if(sectorInformations!=null && sectorInformations.size()>0){
                        objects1.addAll(sectorInformations);
                    }
                }
                objectObjectHashMap.put("limit_calculation_for_commerical_needs", objects1);
                list.add(objectObjectHashMap);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> sectorinformationAndDealerinformation1(Map<String, Object>  map ) {
        String dealerName = (String)map.get("dealerName");
        String sector = (String)map.get("sector");
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("dealerName", dealerName);
        ArrayList<SectorInformation> objects1 = new ArrayList<>();
        SectorInformation sectorInformation = new SectorInformation();
        sectorInformation.setSector(sector);
        //根据sector查对应得sectorinformation详细数据
        List<SectorInformation> sectorInformations = sectorInformationMapper.selectSectorInformationList(sectorInformation);
        objects1.addAll(sectorInformations);
        objectObjectHashMap.put("limit_calculation_for_commerical_needs", objects1);
        return objectObjectHashMap;
    }

    @Override
    public List<Map<String, Object>> approvalLimitCalculationForCommericalNeeds(Map<String, Object> map) {
        //先通过dealername查dealerinformation对应得sector
//        String dealerName = (String)map.get("dealerName");
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        int a = 1;
        //根据instanceid，和dealername,查limit_calculation_for_commerical_needs对应得数据
        String instanceId = (String) map.get("instanceId");
        List<String> dealerName = (List<String>) map.get("dealerName");
        for (String maps : dealerName) {
            LimitCalculationForCommericalNeeds dealerInformation = new LimitCalculationForCommericalNeeds();
            dealerInformation.setDealername(maps);
            dealerInformation.setInstanceId(instanceId);
            List<LimitCalculationForCommericalNeeds> dealerInformations = limitCalculationForCommericalNeedsMapper.selectLimitCalculationForCommericalNeedsList(dealerInformation);
            Map<String, Object> objectObjectHashMap = new HashMap<>();
            ArrayList<Map<String, Object>> objects = new ArrayList<>();
            for (LimitCalculationForCommericalNeeds aa : dealerInformations) {
                HashMap<String, Object> objectObjectHashMap1 = new HashMap<>();
                objectObjectHashMap1.put("id", aa.getId());
                objectObjectHashMap1.put("sector", aa.getSector());
                objectObjectHashMap1.put("model", aa.getModel());
                objectObjectHashMap1.put("avgLoanAmt", aa.getAip());
                objectObjectHashMap1.put("actualAvgDso", aa.getAtd());
                objectObjectHashMap1.put("estimatedannualwholesaleunits", aa.getEstimatedannualwholesaleunits());
                objectObjectHashMap1.put("creditlimitfornewvehicle", aa.getCreditlimitfornewvehicle());
                objects.add(objectObjectHashMap1);
            }
            objectObjectHashMap.put("dealerName", maps);
            objectObjectHashMap.put("limit_calculation_for_commerical_needs", objects);
            list.add(objectObjectHashMap);
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> selectplmWhereDealerName(List<String> map) {
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMM");
            String format = sdf1.format(new Date());
            List<String> resultList = new ArrayList<String>();
            List<String> stringList = new ArrayList<>();
            Calendar cal = Calendar.getInstance();
            //近六个月
            String dateByFirst = getDateByFirst();
            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
            Date date = formatDate.parse(dateByFirst);
            resultList.add(sdf1.format(monthAddNum(date,-1)));
            resultList.add(sdf1.format(monthAddNum(date,-2)));
            resultList.add(sdf1.format(monthAddNum(date,-3)));
            resultList.add(sdf1.format(monthAddNum(date,-4)));
            resultList.add(sdf1.format(monthAddNum(date,-5)));
            resultList.add(sdf1.format(monthAddNum(date,-6)));
            Collections.reverse(resultList);
            stringList.add("Item");
            for (String res : resultList) {
                stringList.add(res);
            }

            ArrayList<Map<String, Object>> list = new ArrayList<>();
            for (String maps : map) {
                HashMap<String, Object> map1 = new HashMap<>();
                Plm plm = new Plm();
                plm.setDealernamecn(maps);
                List<Plm> plms = plmMapper.selectPlmList(plm);
                if (StringUtils.isNotEmpty(plms)) {
//                throw new BaseException("plm表没对应得数据,STOCK AUDIT PERFORMANCE(FOR RECENT 6 MONTHS)就没数据");

//            ArrayList<Plm> objects = new ArrayList<>();
//
//            objects.addAll(plms);
                    Plm plm12 = plms.get(0);
                    map1.put("dealerName", maps);
                    map1.put("title", stringList);
                    ArrayList<Map<String, Object>> objects = new ArrayList<>();
                    List<String> items = new ArrayList<>();
                    items.add("DPD(units)");
                    items.add("SOT");
                    items.add("DC");

                    for (String it : items) {
                        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                        objectObjectHashMap.put("Item", it);
                        for (String nianyue : resultList) {
                            for (Plm plm1 : plms) {
//                    HashMap<String, Object> objectObjectHashMap1 = new HashMap<>();

//                        objectObjectHashMap.put(nianyue, "");

                                if (nianyue.equals(plm1.getMonth().replace("-",""))) {
                                    if (it.equals("DPD(units)")) {
                                        objectObjectHashMap.put(nianyue, plm1.getDpd());
                                    }
                                    if (it.equals("SOT")) {
                                        objectObjectHashMap.put(nianyue, plm1.getSot());
                                    }
                                    if (it.equals("DC")) {
                                        objectObjectHashMap.put(nianyue, plm1.getDc());
                                    }
//                        objectObjectHashMap.put(nianyue,plm1);
                                }
//                    objectObjectHashMap.putAll(objectObjectHashMap1);

                            }
                        }
                        objects.add(objectObjectHashMap);

                    }

                    map1.put("row", objects);
                    list.add(map1);
                }
            }
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    //保存年审临时信息
    @Override
    public AjaxResult yearAuditSave(YearAuditSaveDTO yearAuditSaveDTO) {
        //1.更新的所有notes
        Notes notes = new Notes();
        BeanUtils.copyProperties(yearAuditSaveDTO, notes);
        notesMapper.updateNotes(notes);

        //2. 更新 SalesPerformanceAndTarget
        if (CollectionUtil.isNotEmpty(yearAuditSaveDTO.getSalesPerformanceAndTargets())) {
            yearAuditSaveDTO.getSalesPerformanceAndTargets().forEach(e -> {
                SalesPerformanceAndTarget salesPerformanceAndTarget = new SalesPerformanceAndTarget();
                BeanUtils.copyProperties(e, salesPerformanceAndTarget);
                salesPerformanceAndTargetMapper.updateSalesPerformanceAndTarget(salesPerformanceAndTarget);
            });
        }
        //3.更新 LimitCalculationForCommericalNeeds
        if (CollectionUtil.isNotEmpty(yearAuditSaveDTO.getLimitCalculationForCommericalNeeds())) {
            yearAuditSaveDTO.getLimitCalculationForCommericalNeeds().forEach(f -> {
                LimitCalculationForCommericalNeeds limitCalculationForCommericalNeeds = new LimitCalculationForCommericalNeeds();
                BeanUtils.copyProperties(f, limitCalculationForCommericalNeeds);
                limitCalculationForCommericalNeedsMapper.updateLimitCalculationForCommericalNeeds(limitCalculationForCommericalNeeds);
            });
        }
        //4.更新 OtherFinancingResource
        if (CollectionUtil.isNotEmpty(yearAuditSaveDTO.getOtherFinancingResources())) {
            yearAuditSaveDTO.getOtherFinancingResources().forEach(g -> {
                OtherFinancingResource otherFinancingResource = new OtherFinancingResource();
                BeanUtils.copyProperties(g, otherFinancingResource);
                otherFinancingResourceMapper.updateOtherFinancingResourceByid(otherFinancingResource);
            });
        }
        //5.等待以上更新能对接后再加上;
        AjaxResult result = new AjaxResult();
        result.put("code", 200);
        result.put("msg", "保存更新成功");
        return result;
    }

    @Override
    public AjaxResult reminder(String instanceId) {
        org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(instanceId).singleResult();
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        String taskId = task.getId();
        ActRuIdentitylink actRuIdentitylink = actRuIdentitylinkMapper.selectActRuIdentitylinkByTaskId(taskId);
        String groupId = actRuIdentitylink.getGroupId();    // 获取组
        String userName = actRuIdentitylink.getUserId();    // 获取用户，返回的是用户名
        if (!StringUtil.isEmpty(groupId)) {
            // 根据组查对应组成员id，在查到对应的用户对象信息
            if(groupId.equals("保险购买确认")||groupId.equals("保证金调整确认") ||groupId.equals("盈余保证金操作")){
                groupId = "op";
            }else if(groupId.equals("保证金调整审核") ||groupId.equals("盈余保证金操作审核") ){
                groupId = "opManager";
            }else if(groupId.equals("UW-Requester")){
                groupId = "underwriter";
            }
            List<SysUser> userList = sysPostMapper.selectUserListByPostCode(groupId);
            if (userList != null && userList.size() > 0) {
                for (SysUser sysUser : userList) {
                    // 调用发送邮件方法
                    try {
                        sendMailByEmailInfo(sysUser,instanceId);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            if (!StringUtil.isEmpty(userName)) {
                // 根据user_name查询用户
                SysUser sysUser = userMapper.selectUserByUserName(userName);
                // 调用发送邮件方法
                try {
                    if (sysUser == null) {
                        actRuIdentitylinkMapper.updateActRuIdentitylinkByTaskId(taskId);
                        SysUser ryUser = userMapper.selectUserById(2L);
                        sendMailByEmailInfo(ryUser,instanceId);
                    } else {
                        sendMailByEmailInfo(sysUser,instanceId);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public AjaxResult waitForSaveNote(WaitForSaveNoteDTO waitForSaveNoteDTO) {
        waitForSaveNoteDTO.setId(null);
        Notes notes1 = notesMapper.selectNotesByInstanceId(waitForSaveNoteDTO.getInstanceId());
        BeanUtils.copyProperties(waitForSaveNoteDTO, notes1);
        notesMapper.updateNotes(notes1);
        return new AjaxResult(200, "保存成功");

    }

    @Override
    public List<AnnualReviewy> listMineDo() {
        return annualReviewyMapper.listMineDo(SecurityUtils.getUsername(), 3);
    }

    @Override
    public List<String> getWorkName() {

        List<String> workNames = annualReviewyMapper.getWorkName();
        List<String> lists = new ArrayList<>();
        for (String workName : workNames) {
            if(!(workName.contains("Select")) && !(workName.contains("1")) && !(workName.contains("2"))){
                lists.add(workName);
            }
        }
        return lists;
    }

    @Override
    public List<String> getWorkflowFormData(String instanceId) {
        List<String> workNames = annualReviewyMapper.getWorkflowFormData(instanceId);
        return workNames;
    }


    public void sendMailByEmailInfo(SysUser sysUser,String instanceId) throws IOException {
        if(isSendEmal!=null && isSendEmal.equals("true")) {
            //申请流程名称
            String str = actWorkflowFormDataMapper.selectByInstanceId(instanceId);

            //经销商名称
            List<Map<String, String>> dealerNames = actWorkflowFormDataMapper.getDealerNameByInstanceId(instanceId);

            String names = "";
            for (Map<String, String> dealerName : dealerNames) {
                dealerName.values();
                //获取经销商中英文
                names = names + "---" + StringUtils.join(dealerName.values(), "---");
            }
            //String content = "网站链接:"+url+"\n|--------|申请流程名称："+str+"\n|----------|经销商名称:"+names;
            String ln = "<br>";
            String content = msg + ln + "申请流程名称:" + str + ln + "经销商名称：" + names + ln + "网站链接:" + "<a href ='" + url + "'>点此登录</a>";
            // 获取邮箱
            String email = sysUser.getEmail();
            if (!StringUtil.isEmpty(email)) {
                try {
                    // 测试文本邮件发送（无附件）
                    String to = email;
                    String title = "[催办]您有待办任务请审批";
                    //带附件方式调用
                    new EmailUtil(from, mailSender).sendMessageCarryFiles(to, title, content, null);
                    // return AjaxResult.success();
                } catch (Exception e) {
                    // e.printStackTrace();
                    // return AjaxResult.error(e.getMessage());
                }
            }
        }
    }

    @Override
    public List<ApprovalStatusVO> selectAnnualReviewyVODMList(AnnualReviewy annualReviewy){
        ArrayList<ApprovalStatusVO> list = new ArrayList<>();
        SysPost sysPost = new SysPost();
        sysPost.setPostName("dm");
        List<SysPost> sysPosts = sysPostMapper.selectPostList(sysPost);
        if(CollectionUtil.isNotEmpty(sysPosts)){
            List<AnnualReviewy> annualReviewies = annualReviewyMapper.listDmInstanceId(sysPosts.get(0).getPostId().toString());
            for(AnnualReviewy ar : annualReviewies){
                ProposalByCommericalAndMarketing proposalByCommericalAndMarketing = new ProposalByCommericalAndMarketing();
                proposalByCommericalAndMarketing.setInstanceId(ar.getInstanceId());
                List<ProposalByCommericalAndMarketing> pbam = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingListgroupby(proposalByCommericalAndMarketing);
                if(CollectionUtil.isNotEmpty(pbam)){
                    for (ProposalByCommericalAndMarketing pbams : pbam){
                        ApprovalStatusVO approvalStatusVO = new ApprovalStatusVO();
                        approvalStatusVO.setInstanceId(pbams.getInstanceId());
                        approvalStatusVO.setSector(pbams.getSector());
                        approvalStatusVO.setDealerName(pbams.getDealername());
                        List<DealerInformation> dealerInformation = dealerInformationMapper.selectDealerInformationByDealerName(pbams.getDealername());
                        if(CollectionUtil.isNotEmpty(dealerInformation)){
                            approvalStatusVO.setDealerNameEn(dealerInformation.get(0).getEnName());
                            approvalStatusVO.setGroup(dealerInformation.get(0).getGroupName());
                        }
//                        approvalStatusVO.setStatus();
                        CreditCondition creditCondition = new CreditCondition();
                        creditCondition.setDealername(pbams.getDealername());
                        creditCondition.setSector(pbams.getSector());
                        creditCondition.setLimittype("NORMAL");
                        creditCondition.setInstanceid(pbams.getInstanceId());
                        List<CreditCondition> creditConditions = creditConditionMapper.selectCreditConditionList(creditCondition);
                        if(CollectionUtil.isNotEmpty(creditConditions)){
                            approvalStatusVO.setExpiryDate(creditConditions.get(0).getExpireddate());
                        }
                        List<AnnualReviewy> annualReviewy1 = annualReviewyMapper.selectAnnualReviewyByInstanceIdList(pbams.getInstanceId());
                        approvalStatusVO.setCompletedDate(annualReviewy1.get(0).getUpdateTime());
                        ProposalByCommericalAndMarketing proposalByCommericalAndMarketing1 = new ProposalByCommericalAndMarketing();
                        proposalByCommericalAndMarketing1.setInstanceId(pbams.getInstanceId());
                        proposalByCommericalAndMarketing1.setDealername(pbams.getDealername());
                        proposalByCommericalAndMarketing1.setSector(pbams.getSector());
                        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketing1);
                        double sumApproved = 0;
                        double sumProposal = 0;
                        if(CollectionUtil.isNotEmpty(proposalByCommericalAndMarketings)){
                            for(ProposalByCommericalAndMarketing pb : proposalByCommericalAndMarketings){
                                if(ObjectUtil.isEmpty(pb.getApprovedLimit())){
                                    pb.setApprovedLimit(new Long(0));
                                }
                                sumApproved = Arith.add(sumApproved, pb.getApprovedLimit());
                                if(ObjectUtil.isEmpty(pb.getProposalLimit())){
                                    pb.setProposalLimit(new Long(0));
                                }
                                sumProposal = Arith.add(sumProposal,pb.getProposalLimit());
                            }
                        }
                        approvalStatusVO.setOriginalLimit(Convert.getDoubleString(sumApproved));
                        approvalStatusVO.setUpdatedLimit(Convert.getDoubleString(sumProposal));
                        proposalByCommericalAndMarketing1.setLimitType("NORMAL");
                        List<ProposalByCommericalAndMarketing> proposalByCommericalAndMarketings1 = proposalByCommericalAndMarketingMapper.selectProposalByCommericalAndMarketingList(proposalByCommericalAndMarketing1);
                        if(CollectionUtil.isNotEmpty(proposalByCommericalAndMarketings1)){
                            approvalStatusVO.setOriginalSecurityRatio(proposalByCommericalAndMarketings1.get(0).getApprovedCashDeposit());
                            approvalStatusVO.setUpdatedSecurityRatio(proposalByCommericalAndMarketings1.get(0).getProposalCashDeposit());
                        }
                        list.add(approvalStatusVO);
                    }
                }
            }
            return list;
        }
        return null;
    }

    @Override
    public String fileZip(String instanceId) {
        if(StringUtils.isNotEmpty(instanceId)){
            List<Fileupload> fileuploadList = fileuploadService.selectFileuploadListByInstanceIdAndDm(instanceId);
            if(fileuploadList !=null &&  fileuploadList.size()>0){
                List<File> files = new ArrayList<>();
                for (Fileupload fileupload : fileuploadList) {
                    String substring = fileupload.getFileName().substring(8);
                    System.out.println(RuoYiConfig.getProfile()+substring);
                    File file = new File(RuoYiConfig.getProfile()+substring);
                    files.add(file);
                }
                String zipFilePath = "/profile/template/zips/"+IdUtils.get16UUID()+"/";
                String fileName = instanceId+".zip";
                compressToZip(files, "/"+RuoYiConfig.getProfile()+zipFilePath, fileName);
                return "/profile"+zipFilePath+fileName;
            }

        }
       return null;
    }

    @Override
    public List<HAml> selectAmlInfoList(String instanceId) {
        //这里写AML

        List<BasicInformation> basicInformations1 = basicInformationMapper.selectDealerGroupByDealerName(instanceId);

        ArrayList<HAml> respList = new ArrayList<>();
        for (BasicInformation basicInformation : basicInformations1) {
            ArrayList<HAml> list = new ArrayList<>();
            List<DealerInformation> dealerInformations = dealerInformationMapper.selectDealerInformationByDealerName(basicInformation.getDealerNameCN());
            DealerInformation dealerInformation = dealerInformations.get(0);
            if(StringUtils.isNotEmpty(dealerInformation.getLegalRepresentativeCN())){
                HAml hAml = new HAml();
                hAml.setInstanceId(instanceId);
                hAml.setDealerName(basicInformation.getDealerNameCN());
                hAml.setPosition("法人");
                hAml.setName(dealerInformation.getLegalRepresentativeCN());
                list.add(hAml);
            }
            if(StringUtils.isNotEmpty(basicInformation.getDealerNameCN())){
                HAml dealerAML = new HAml();
                dealerAML.setInstanceId(instanceId);
                dealerAML.setDealerName(basicInformation.getDealerNameCN());
                dealerAML.setPosition("经销商");
                dealerAML.setName(basicInformation.getDealerNameCN());
                list.add(dealerAML);
            }
            if(StringUtils.isNotEmpty(dealerInformation.getShareholderStructure())){
                String shareholderStructure = dealerInformation.getShareholderStructure();
                String[] split = shareholderStructure.split(";");
                for(String sp: split){
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    ArrayList<String> objects = new ArrayList<>();
                    StringTokenizer stringTokenizer = new StringTokenizer(sp, "#:");
                    while(stringTokenizer.hasMoreElements()){
                        objects.add(stringTokenizer.nextToken());
                    }
                    if(objects.size()==3) {
                        HAml guDong = new HAml();
                        guDong.setInstanceId(instanceId);
                        guDong.setDealerName(basicInformation.getDealerNameCN());
                        guDong.setPosition("股东");
                        guDong.setName(objects.get(1));
                        list.add(guDong);
                    }
                }
            }
            if(StringUtils.isNotEmpty(dealerInformation.getGm())){
                HAml guDong = new HAml();
                guDong.setInstanceId(instanceId);
                guDong.setDealerName(basicInformation.getDealerNameCN());
                guDong.setPosition("总经理");
                guDong.setName(dealerInformation.getGm());
                list.add(guDong);
            }
            //查该经销商下对应得担保人和担保机构
            Securities securities = new Securities();
            securities.setInstanceId(instanceId);
            securities.setDealername(basicInformation.getDealerNameCN());
            List<Securities> securitiesList1 = securitiesMapper.selectSecuritiesList(securities);
            for(Securities se: securitiesList1){
                if(StringUtils.isNotEmpty(se.getGuaranteeType())){
                    if(se.getGuaranteeType().equals("personal")){
                        if(!StringUtils.isEmpty(se.getProposalNameCN())){
                            HAml ren = new HAml();
                            ren.setInstanceId(instanceId);
                            ren.setDealerName(basicInformation.getDealerNameCN());
                            ren.setPosition("担保人");
                            ren.setName(se.getProposalNameCN());
                            list.add(ren);
                        }
                    }
                }
            }
            for(Securities se: securitiesList1){
                if(StringUtils.isNotEmpty(se.getGuaranteeType())){
                    if(se.getGuaranteeType().equals("corporate")){
                        if(!StringUtils.isEmpty(se.getProposalNameCN())){
                            HAml gongSi = new HAml();
                            gongSi.setInstanceId(instanceId);
                            gongSi.setDealerName(basicInformation.getDealerNameCN());
                            gongSi.setPosition("担保公司");
                            gongSi.setName(se.getProposalNameCN());
                            list.add(gongSi);
                        }
                    }
                }
            }
            if(list.size()>0){
                Map<String, List<HAml>> collect = list.stream().collect(Collectors.groupingBy(HAml::getName));
                for (String key : collect.keySet()) {
                    List<HAml> sums = collect.get(key);
                    HAml respAml = new HAml();
                    respAml.setInstanceId(instanceId);
                    respAml.setDealerName(basicInformation.getDealerNameCN());
                    respAml.setName(key);
                    respAml.setPosition("");
                    StringBuffer position = new StringBuffer();
                    for (HAml sum : sums) {
                        position.append(sum.getPosition()).append("/");
                    }
                    if (position.length()>0) {
                        position.deleteCharAt(position.length() - 1);
                        respAml.setPosition(position.toString());
                    }
                    respList.add(respAml);
                }
            }
        }
        for (HAml aml : respList) {
            if(StringUtils.isNotEmpty(aml.getName())){
                String amlName = amlMapper.getAmlName(aml.getName());

                if(StringUtils.isNotEmpty(amlName)){
                    aml.setIsBlackList(0);
                    aml.setNote("Hit AML list. Further investigate");
                }else{
                    aml.setIsBlackList(1);
                    aml.setNote("No Negative information.");
                }

                String rptName = rptMapper.getRptName(aml.getName());
                if(StringUtils.isNotEmpty(rptName)){
                    aml.setIsRelatedList(0);
                }else{
                    aml.setIsRelatedList(1);
                }
            }else{
                aml.setIsBlackList(1);
                aml.setIsRelatedList(1);
                aml.setNote("No Negative information.");
            }
        }
        return respList;
    }



    public  void compressToZip( List<File> files, String zipFilePath, String zipFilename) {
        File zipPath = new File(zipFilePath);
        if (!zipPath.exists()) {
            zipPath.mkdirs();
        }
        File zipFile = new File(zipPath + File.separator + zipFilename);
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (File f : files) {
                writeZip(f, "", zos);
            }
            //文件压缩完成后，删除被压缩文件
            // boolean flag = deleteDir(sourceFile);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    public  void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.isDirectory()) {
            //目录
            parentPath += file.getName() + File.separator;
            File[] files = file.listFiles();
            for (File f : files) {
                writeZip(f, parentPath, zos);
            }
        } else {
            //文件
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                //指定zip文件夹
                ZipEntry zipEntry = new ZipEntry(parentPath + file.getName());
                zos.putNextEntry(zipEntry);
                int len;
                byte[] buffer = new byte[1024 * 10];
                while ((len = bis.read(buffer, 0, buffer.length)) != -1) {
                    zos.write(buffer, 0, len);
                    zos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
    }

    public List<HAml> createAmlList(String instanceId,String dealerName){
        ArrayList<String> positions = new ArrayList<>();
        ArrayList<HAml> hAmls = new ArrayList<>();
        positions.add("法人");
        positions.add("股东");
        positions.add("总经理");
        positions.add("担保人");
        positions.add("担保公司");
        int i = 1;
        for (String position : positions) {
            HAml hAml = new HAml();
            hAml.setSort(i);
            hAml.setInstanceId(instanceId);
            hAml.setDealerName(dealerName);
            hAml.setPosition(position);
            hAmls.add(hAml);
            i++;
        }
        return  hAmls;
    }

    @Override
    @Async
    public <T> String  saveDbLog(String operType, String operMethod,String title , String instanceId, T oldBean ,T newBean,String screenName) {
        try {
            SysDbOperLog sysDbOperLog = new SysDbOperLog();
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            sysDbOperLog.setOperIp(ip);
            sysDbOperLog.setOperName(SecurityUtils.getNickName());
            sysDbOperLog.setInstanceid(instanceId);
            sysDbOperLog.setAccount(SecurityUtils.getUsername());
            sysDbOperLog.setLogType("业务操作日志");
            if(!StringUtils.isEmpty(instanceId)){
                if(instanceId.contains("TL")){
                    sysDbOperLog.setScreenName("temp limit");
                }else if(instanceId.contains("2T")){
                    sysDbOperLog.setScreenName("2nd-tier cash deposit");
                }
                else if(instanceId.contains("ALD")){
                    sysDbOperLog.setScreenName("active limit decrease");
                }
                else if(instanceId.contains("ALT")){
                    sysDbOperLog.setScreenName("active limit transfer");
                }
                else if(instanceId.contains("ARE")){
                    sysDbOperLog.setScreenName("annual review extension");
                }
                else if(instanceId.contains("AR")){
                    sysDbOperLog.setScreenName("Annual Review");
                }
                else if(instanceId.contains("CD")){
                    sysDbOperLog.setScreenName("change conditions");
                }
                else if(instanceId.contains("CA")){
                    sysDbOperLog.setScreenName("试驾车抵押合同流程");
                }
                else if(instanceId.contains("CB")){
                    sysDbOperLog.setScreenName("Credit bridge");
                }
                else if(instanceId.contains("DD")){
                    sysDbOperLog.setScreenName("deposit% decrease");
                }
                else if(instanceId.contains("DI")){
                    sysDbOperLog.setScreenName("deposit% increase");
                }
                else if(instanceId.contains("LRA")){
                    sysDbOperLog.setScreenName("Limit Re-Activation");
                }
                else if(instanceId.contains("NA")){
                    sysDbOperLog.setScreenName("new application");
                }
                else if(instanceId.contains("PLID")){
                    sysDbOperLog.setScreenName("permanent limit increase/decrease");
                }
                else if(instanceId.contains("PLT")){
                    sysDbOperLog.setScreenName("permanent Limit transfer");
                }
                else if(instanceId.contains("PL")){
                    sysDbOperLog.setScreenName("parking location registration");
                }
                else if(instanceId.contains("-")){
                    sysDbOperLog.setScreenName("startContract");
                }
                else if(instanceId.contains("TM")){
                    sysDbOperLog.setScreenName("termination");
                }
                else if(instanceId.contains("WLS")){
                    sysDbOperLog.setScreenName("WFS Limit Set-Up");
                }
                else if(instanceId.contains("IC")){
                    sysDbOperLog.setScreenName("保险信息变更");
                }
                else if(instanceId.length()>17){
                    sysDbOperLog.setScreenName("startDM/startPLM");
                }
            }else{
                sysDbOperLog.setScreenName(screenName);
            }
            sysDbOperLog.setOperMethod(operMethod);
            sysDbOperLog.setOperTime(new Date());
            sysDbOperLog.setTitle(title);
            if(operType.equals("1")){
                sysDbOperLog.setOperType("新增");
                String newB = JSON.toJSONString(newBean);
                sysDbOperLog.setAfterModifi(newB);
            }else if (operType.equals("2")){
                sysDbOperLog.setOperType("删除");
                String oldB = JSON.toJSONString(oldBean);
                sysDbOperLog.setBeforeModifi(oldB);
            }else if (operType.equals("3")){
                sysDbOperLog.setOperType("修改");
                String oldB = JSON.toJSONString(oldBean);
                sysDbOperLog.setBeforeModifi(oldB);
                String newB = JSON.toJSONString(newBean);
                sysDbOperLog.setAfterModifi(newB);
                String changedFields = com.ruoyi.common.utils.bean.BeanUtils.getChangedFields(oldBean, newBean);
                if(!StringUtils.isEmpty(changedFields)){
                    sysDbOperLog.setColumnModifi(changedFields);
                }
            }
            sysDbOperLogMapper.insertSysDbOperLog(sysDbOperLog);
        }catch (Exception e){
            e.printStackTrace();
        }

       return null;
    }
    public  Date monthAddNum(Date time, Integer num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MONTH, num);
        Date newTime = calendar.getTime();
        return newTime;
    }

    public  String getDateByFirst() {
        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        // 将日期设置为当前月份的第一天
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return year+"-"+ month+"-"+ day;
    }
}
